Charts
Try it live — 50,000 rows, the panel and every option on this page.
Charting is split the same way the rest of the grid is: the model is Community, the renderers and the panel are Enterprise.
| Package | What you get | |
|---|---|---|
| Model | @kanunilabs/datagrid-react | useGridChartData() — categories and aggregated series, ready for any chart library |
| Panel | @kanunilabs/datagrid-react-enterprise | The dock panel, six renderers, pickers, fullscreen, cross-filtering |
The panel (Enterprise)
One prop:
import { EnterpriseDataGrid } from '@kanunilabs/datagrid-react-enterprise';
<EnterpriseDataGrid
licenseKey={key}
dataSource={rows}
rowKey="id"
columns={columns}
charting
/>
That adds a Chart button to the toolbar and a Chart by this column entry to every column header's right-click menu. The panel docks above the grid — not over it, because watching the chart follow a filter you just applied is the point, and a modal would hide the grid doing the filtering. When the grid needs the room, Pop out turns the panel into a window over it (A floating window).
The pickers are built from the grid's own column model, so there is no list to keep in sync: hide a column and it leaves the pickers with it.
Options
<EnterpriseDataGrid
charting={{
crossFilter: true, // clicking a category filters the grid. Default false.
defaultOpen: true, // dock the panel open instead of waiting for the button.
height: 280, // docked canvas height in px, until the user drags it. Default 280.
floating: true, // open as a window over the grid (or { x, y, width, height }).
container: box, // or put the chart in an element of yours instead (below).
defaultSpec: { categoryColumnId: 'region' },
defaultStacking: 'stacked', // 'grouped' (default) | 'stacked' | 'normalized'
defaultFormat: { title: 'Sales by region', legend: 'right', dataLabels: true },
onFormatChange: (format) => save(format), // the reader's Format edits, to keep
labels: { title: 'Grafik' },
}}
/>
The docked panel's height is the user's to change. A divider under the
panel drags the chart shorter or taller — or focus it and use ↑ /
↓ (with Shift for bigger steps), Home and
End. In a box of fixed height, such as a modal, it stops where the grid
would keep fewer than 80 px of rows (its column header, footer and bars are not
counted against that); the chart itself goes no lower than 120. The chart is
also shown no taller than that when it opens and when the box resizes, so a
short dialog never opens with the grid squeezed out; the height the user chose
comes back when there is room. In a box too short for the chart's toolbar as it
wraps, its smallest size and those rows, the rows come first: the toolbar keeps
to one line that scrolls sideways, and the chart may go below 120 px. The height
is part of the chart's state (dockHeight), so getViewState() saves it and a
restored view reopens the chart at it; without one the panel uses height.
recharts is an optional peer dependency, loaded only when the panel is
first opened. A grid that never charts does not pull it into the bundle:
npm i recharts
Without it the grid builds and runs as usual; opening the chart panel says the
package is needed. (Up to @kanunilabs/datagrid-react-enterprise 1.2.0 the
published build imported recharts at load time despite this — an app without
it failed to start, and one with it carried it in the main bundle. A build
check now keeps optional peers behind a dynamic import().)
Chart types
column · bar · line · area · pie · donut · radar · scatter ·
bubble · waterfall · funnel · treemap · heatmap · rangeBar · box
A radar puts one spoke per category round a circle and draws each series as a polygon over them, on rings at round values — for comparing a few series across the same handful of categories. Each vertex has a tooltip; in the JavaScript panel a click on one cross-filters like a bar.
The list is a registry, not a switch. Register your own renderer — D3,
ECharts, hand-written SVG — and it appears in the type picker beside the
built-ins:
import { chartRegistry } from '@kanunilabs/datagrid-react-enterprise';
chartRegistry.register({
def: { id: 'radar', label: 'Radar', requiresCategory: true },
render: (model, ctx) => <MyRadar model={model} colors={ctx.colors} />,
});
model is the same ChartModel described below; ctx carries the locale,
colours, hidden-series set, the measured canvas size, the series layout
(ctx.stacking) and the cross-filter callback.
Waterfall, funnel, treemap and heatmap
- Waterfall: each category moves a running total. Rises and falls are coloured apart, a dashed connector carries the total to the next bar, and a closing Total bar stands on zero.
- Funnel: the categories as stages, in the order they come (the order is the process, so it is never re-sorted). Each stage is labelled with its value and its share of the first stage.
- Treemap: a rectangle per category with its area proportional to the value, laid out to stay close to square. Zero and negative values take no area.
- Heatmap: categories across, series down, each cell coloured by its value on one scale over the whole matrix. Values print in the cells that have room.
The first three show one series; the heatmap shows every visible series. Each cell or bar has a tooltip and takes part in cross-filtering like a column.
Range
A floating bar per category, from one series to the other: the lowest and
highest price of each month, a planned against an actual figure. Pick two
series, for example the same column with min and with max:
charting={{
defaultType: 'rangeBar',
defaultSpec: {
categoryColumnId: 'month',
series: [
{ columnId: 'price', aggregate: 'min' },
{ columnId: 'price', aggregate: 'max' },
],
},
}}
Either series can be the low one: each category runs from its own smaller value to its larger one. Both ends are labelled, and each end is drawn in its own series' colour so the legend matches the chart. A category missing either value draws no bar, and with only one series visible there is no range to draw. The tooltip shows both ends; a click cross-filters like a bar.
Box plot
A box per category shows the spread of one number column, where every other type reduces the category to a single number: the box spans the first to the third quartile with a line at the median, the whiskers reach the furthest values within 1.5 × the box's height, and anything beyond them is a dot. The series has no aggregate — the box is the values themselves — and a text column picked for it moves to the first number column. Dates and numbers on the category axis group by the same intervals as the other charts; past 30 categories the most populous ones are kept and the panel says so. The tooltip lists the five numbers and the count; a click on a box cross-filters like a bar. The values are held to find the medians, so it is computed on the main thread, as scatter is.
Scatter and bubble
Every other type is a group-by: a category and an aggregate per series. Scatter and bubble are not. They plot one point per row:
- the category picker becomes the x axis, offering number and date columns (a date axis reads as dates);
- each series is a y column, with no aggregate to choose;
- a bubble adds a size column, and the bubble's area follows the value, which is how a reader compares circles.
A million points is not a chart anyone can read, and an SVG with a million circles is not a page that responds. So each series shows at most 2,000 points. Past that, rows are taken evenly through the current order, every k-th row, and the panel says how many of how many it shows. The tooltip prints x, y and size the way their own columns print them.
Without the panel, controller.computeChartXYData(spec) returns the same
points, and useGridChartXYData(controller, spec) (React) and
watchChartXYData (JavaScript) keep them current.
Grouped, stacked and 100% stacked
With two or more series, column, bar, line and area charts offer three layouts in the panel's toolbar:
- Grouped: the series stand side by side. The default.
- Stacked: each category is one bar (or band) cut into the series, so its height is the total and each segment is one series' part of it.
- 100% stacked: every category is the same height and each segment is a share of it. The value axis reads in percent.
The rules are the ones spreadsheet charts use. Negative values stack downward from zero, apart from the positives. A series with nothing to total in a category leaves a gap, and the rest stack past it. A 100% share is taken of the absolute total, so a negative value takes its share below the axis. A stack has one baseline, so the automatic second axis (below) does not apply. The tooltip always shows the real value, with the share beside it in 100%.
Open on a layout with defaultStacking. In JavaScript the same option exists
on charting, and grid.chartPanel.open({ stacking: 'normalized' }) opens
straight into it. Pie and donut show a single series and have no layout to
choose.
Swapping categories and series
Swap category and series turns the chart around: each series becomes a category and each category a series. "Revenue and cost, per region" becomes "each region's revenue and cost" — the same numbers, read the other way, with nothing aggregated again. Press it again to swap back. It is offered for every type except the X-Y ones (scatter, bubble) and the box plot, where a point or a box has no category to swap.
While swapped, the categories are column names, so a click on a mark filters nothing (cross-filtering waits until you swap back), and the bucket bounds of a date or number axis no longer apply. At most 24 categories become series; past that the chart says it is cut. Series values print in their column's format when every series read the same column, and as plain numbers otherwise. The legend switches and the zoom start over, since the positions they named changed meaning.
The swap is part of the chart state (switched: true, no key when not), so the
saved view keeps it; open({ switched: true }) opens swapped.
Unlinking a chart from the grid
Unlink freezes the chart as it is: it keeps the data it had and no longer follows the grid — filter, sort, edit or add rows and the chart stays put, which is what you want when comparing "before" with "after". The type (among types that read the same kind of data), the format, the stacking and the swap still change; what would need fresh data — the columns, the rows it reads, the grouping, or a scatter or box plot from a bar chart — is switched off until you press Link, which draws the grid as it is now. A note under the chart says it is unlinked.
The state has unlinked: true while it is. A saved view keeps that, but not the
data: a restored unlinked chart takes the grid's data once, as it is when it
opens, and keeps that. While unlinked, open() changes to the columns or rows
are recorded and take effect when linked again.
A column's part in charts
A column definition can say what it is to a chart, with chartRole:
const columns = [
{ field: 'region', chartRole: 'category' }, // the panel's first choice for the axis
{ field: 'margin', chartRole: 'series' }, // its first choice for the series
{ field: 'period', chartRole: 'time' }, // a date axis, grouped by calendar
{ field: 'internalId', chartRole: 'excluded' }, // never in a chart
];
'excluded' keeps a column out of the panel's pickers, out of the header menu's
Chart by this column, and out of a charted selection. 'time' treats a
column the grid types as text (say '2026-06') as dates. Without a role the
panel decides by data type, as before.
Format: titles, legend, labels, text, grid and lines
The panel's Format button opens an editor for what a reader usually wants to change before sending a chart on:
- a title above the chart,
- a title for each axis,
- the legend at the top, bottom, left or right, or hidden,
- data labels: each value printed on its mark (on a 100% stack, its share).
- the value scale: linear, or logarithmic for values that span several orders of magnitude. A log axis cannot show zero or a negative value, so those marks are left out. A stacked chart keeps the linear scale.
- the text size and colour of everything written in the chart: tick labels, axis titles, data labels. Titles draw one step larger, data labels one step smaller.
- the category labels: slanted (the default), flat, 45 or 90 degrees.
- the grid lines: along the value axis (the default), along both axes, or none; dashed or solid.
- the series lines: width and dashes for lines, area outlines and radar shapes, and the fill opacity of areas, radar shapes and bubbles.
- the colours of the series: Theme (the default, derived from the grid's accent), Classic, Colour-blind safe (the Okabe–Ito hues), Vivid or One colour (shades of the accent). Every colour of a named palette is moved, where it must be, to at least 3:1 contrast with the chart's background, so the same palette stays visible on a light and a dark colour scheme — measured for all 36 schemes in the test suite.
Every one of these starts at "Default", which leaves the field out of the
format, and a chart drawn without them looks exactly as it did before. From code
the same fields are on ChartFormat, plus a font family and bold or italic text
that the editor does not offer:
defaultFormat: {
font: { family: 'Inter, sans-serif', size: 13, color: '#334155', bold: false, italic: false },
labelAngle: 0, // 'auto' | 0 | 45 | 90
gridLines: 'both', // 'value' | 'both' | 'none'
gridDashed: false,
lineWidth: 3, // 1–6 px
lineDashed: false,
fillOpacity: 0.4, // 0.05–1
palette: 'colorblind', // 'theme' | 'classic' | 'colorblind' | 'vivid' | 'monochrome'
}
For a brand palette, give the colours themselves. colors is used in order and
repeated, exactly as given, and wins over palette — the Colours picker is then
disabled, since the app has already chosen:
defaultFormat: { colors: ['#0f6b5c', '#e07a1f', '#4b5bd6', '#b83280'] } // #rgb or #rrggbb
A saved format is read back defensively: a size, width or opacity out of range and a font or colour that could break out of a style attribute are dropped, not drawn. Text written on a coloured cell (a treemap tile, a heatmap cell) keeps the colour chosen for contrast with that cell.
Open with charting.defaultFormat, and keep the reader's edits with
onFormatChange. The format is plain data, so it fits in a saved view. In
JavaScript the same two options sit on charting, and
grid.chartPanel.open({ format }) opens with a given one.
Axis titles and data labels are drawn inside the chart, and an exported PNG or SVG gets the title as well. A label wider than its bar is left out instead of being printed over the next one; the tooltip still shows that value.
Values print the way their column prints them. Tooltips and data labels run
a sum, avg, min or max through the column's own valueFormatter, the
same rule as the footer. A currency column reads as currency in its chart too.
count and distinct count are row counts and keep a plain number.
Axis labels of your own
The axes print compact numbers (12.5k), the categories, and date groups in the
chosen date format. To write the tick labels yourself, give the grid one
function, charting.axisLabelFormatter. It is asked for every tick label on both
axes, with the raw value and the text the chart would print — return text to
keep the default:
const axisLabelFormatter = useCallback((p: ChartAxisLabelParams) => {
if (p.axis === 'value') return p.percent ? p.text : `€${p.text}`;
// A date group's raw value is its first day, in ms since the epoch.
if (p.columnId === 'orderedAt' && typeof p.value === 'number') {
const d = new Date(p.value);
return `Q${Math.floor(d.getUTCMonth() / 3) + 1} '${String(d.getUTCFullYear()).slice(2)}`;
}
return p.text;
}, []);
<EnterpriseDataGrid charting={{ axisLabelFormatter }} />
| Field | |
|---|---|
axis | 'value' or 'category'. A scatter's or bubble's x axis is the category axis. |
value | The raw value. Value axis: the tick's number. Category axis: the category ('' for a blank) — on an axis grouped by date or number, the group's lower bound as a number (ms for dates); on a scatter's x axis, the x value. |
text | What the chart prints without you: after the number and date format settings, (blank) for a blank. |
columnId | Category axis: the column it reads. |
percent | A 100% stack's value axis: value is a share from 0 to 100. |
secondary | The right-hand axis that much smaller series move to. |
chartType | 'column', 'line', 'waterfall', a type of your own… |
It covers the cartesian types, radar, scatter and bubble, and the axes of the waterfall, heatmap, range and box charts. Pie, donut, funnel and treemap have no axes. Tooltips and data labels keep their own text — except, in the React panel, the built-in tooltip of a waterfall, heatmap, range or box mark, which those layouts draw from the same category text as the axis. A range bar's two end values are printed the way its axis prints numbers, so they follow the formatter as value labels too.
A function cannot be saved, so it lives on the grid's options and never in the
chart's state: getState() and a saved view stay plain data, and the formatter
applies to every chart window of the grid. It runs while the chart draws, so
keep it quick, and stable — in React a new function draws the chart again. A
formatter that throws, or returns something other than a string, leaves that one
label at its default. In JavaScript the same option sits on charting, and a
renderer of your own gets it as ctx.formatAxisLabel.
What the chart aggregates
A chart is a group-by: one category column, one or more value series.
const spec = {
categoryColumnId: 'region',
series: [
{ columnId: 'revenue', aggregate: 'sum' },
{ columnId: 'units', aggregate: 'avg' },
],
source: 'view',
};
Aggregations are the grid's own: sum avg min max count countDistinct —
plus two that only a chart has: first and last, the first and the last number
of each category in the grid's order. With the grid sorted by date, last is
each month's closing value. A sort therefore changes these two (and only these:
the others do not care about order, and a sort leaves their charts alone). A
selection is read in the grid's order too, not the order it was picked in; all
reads the rows in their source order.
They are computed by the same reducers as the footer totals, so a bar and the
footer total of that column can never disagree — blanks are skipped rather than
counted as zero, count is COUNTA, and date columns are parsed before reducing.
A non-numeric column only offers count and countDistinct: summing a warehouse
code runs Number('WH-04'), which is NaN for every row and a silently blank
series.
Which rows
source decides, and the answer is explicit rather than implied:
source | Rows charted |
|---|---|
'view' (default) | Filtered and searched rows, before paging |
'selection' | The selected rows — falling back to 'view' when nothing is selected, so the chart is never silently empty |
'all' | Every source row, ignoring the filter |
'range' | The rows of a cell range, by position (below) |
Charting a cell range
Select cells over several rows, right-click and pick Chart selected cells ▸ and a type: the chart reads exactly those rows, its category the range's first text column and its series the number columns in it. (A single row, or a column from the header menu, charts the whole view as before.) The source picker says which rows — "Selected range (rows 2–5)" — and choosing another source forgets the range.
The grid paints the cells the chart reads: the category column green, the series columns blue, the colours spreadsheet charts use. The range's bottom-right cell has a small handle; drag it up or down and the chart follows as soon as you let go. (A selection made inside the painted range shows over it.)
A range is positions, the way a cell range is: sort or filter the grid and
the chart reads whatever rows now sit at those positions, so what it shows and
what is painted always agree. In the state it is source: 'range' with
rowRange: { start, end } — view positions, 0-based, inclusive — and from code:
chart.open({
categoryColumnId: 'region',
series: [{ columnId: 'revenue', aggregate: 'sum' }],
source: 'range',
rowRange: { start: 0, end: 9 }, // the first ten rows of the view
});
Group header rows take a position too (as they do in a cell range) and are not data, so a range across a group header charts the data rows on either side. Extra chart windows can read ranges of their own; each is painted and has its own handle.
Continuous columns: dates and numbers
A date column has one distinct value per order date. Charted raw, 900 dates become 900 categories, of which the cap below keeps 30 and folds 870 into "Other" — an axis with no chronology left in it. So a date axis is grouped by an interval instead:
const spec = {
categoryColumnId: 'orderedAt',
series: [{ columnId: 'revenue', aggregate: 'sum' }],
categoryBucket: { kind: 'date', unit: 'month' }, // or 'auto'
};
unit is 'auto' (the default) or day · week · month · quarter ·
year. 'auto' measures the data's own span and picks the finest unit that
still fits a readable axis. In the panel this is the By picker, which
appears whenever the category column is a date or a number.
A date axis prints its groups as 2026-03, 2026-Q1 and so on. The Format
editor's Date format (shown only on a calendar axis) prints them in a preset
instead, written by the browser in the chart's language — monthYearLong is
"March 2026" in English and "Mart 2026" in Turkish. In code it is
format.dateFormat. The samples below are as Node 24 writes them; a browser's
own date library may differ in small details:
| Preset | en-US | tr-TR |
|---|---|---|
iso | 2026-03-05 | 2026-03-05 |
numeric | 03/05/2026 | 05.03.2026 |
dayMonth | Mar 5 | 5 Mar |
dayMonthYear | Mar 5, 2026 | 5 Mar 2026 |
long | March 5, 2026 | 5 Mart 2026 |
weekday | Thu, Mar 5 | 5 Mar Per |
month | Mar | Mar |
monthYear | Mar 2026 | Mar 2026 |
monthYearLong | March 2026 | Mart 2026 |
monthNumeric | 03/2026 | 03.2026 |
year | 2026 | 2026 |
Each group prints its first day: a quarter shown as monthYear reads "Jan
2026" for Q1. The groups are calendar intervals in UTC, so the label is the
same in every time zone. Tooltips use the same text; a cross-filter still reads
the group's bounds, not its label.
A numeric column bins the same way:
categoryBucket: { kind: 'number', bins: 20 } // or an exact { size: 50 }
bins is a target: the width is rounded to a 1/2/5×10ⁿ step, so asking for 20
bins over a 0–500.000 range gives ten bins of 50.000 rather than twenty of
23.817.
A bucketed axis behaves differently on purpose:
- Ordered by the interval, never by value.
categoryOrderis ignored. - Empty intervals are kept. A month with no orders is information, and a
chart that closes the gap draws a line straight through it as though the
months were adjacent. Those bars are
NaN, not0. - No "Other" and no top-N. An "Other" in the middle of a time axis is not a
category, it is a hole. When there would be too many intervals the unit is
coarsened instead — every row stays in the chart, the axis just gets less
granular, and
model.bucket.adjustedsays it happened. - Rows whose value will not parse go to the blank category rather than being dropped without trace.
Everything is UTC. Local bucketing would put the same row in a different day
depending on where the browser is, and Date.parse('2023-01-15') is UTC
midnight anyway.
Weeks start on Monday and are labelled by that Monday's date rather than
2023-W03: the ISO week number disagrees with the calendar year at both ends of
December, and a chart axis is a bad place to explain that.
Categories are capped
maxCategories (default 30) keeps the top categories by value and collapses the
rest into a single Other bucket. This is not cosmetic: a grid's category axis
is a raw column, so pointing it at an id column would otherwise ask for a million
categories.
"Other" is folded from the accumulators, not from the finished numbers — so its average is the average of its rows, not the average of the averages it swallowed, and the grand total stays exact.
Two axes when the scales differ
Revenue summed over a million rows is ~10⁸; units over the same rows ~10⁶. On one axis the second series is a hundredth of the chart and draws as a flat line — present in the legend, invisible in the plot. When one series is more than 25× smaller than the largest, it moves to its own right-hand axis automatically. Stacked layouts keep every series on one axis: a stack has a single baseline.
Cross-filtering
Off by default, because a chart click that suddenly re-filters the grid is
surprising. With crossFilter: true, clicking a bar or slice applies that
category as a grid filter. The chart keeps every category on screen — the
picked one at full strength, the rest faint — so the next one is there to
click.
On a bucketed axis the click applies a half-open range —
>= 2023-01-01 AND < 2023-04-01 — not an equality. = '2023-Q1' would match no
row, because "2023-Q1" is a label the engine invented; and an inclusive
between would put the first of April in the first quarter as well as the
second.
Clicking the same mark again clears the filter, and while one is applied the panel says so with a Clear link beside it. Both exist because the condition does not come from an input: the filter row stays empty, so without them the user is looking at 8.000 of 50.000 rows with nothing on screen to press.
The filter replaces whatever was active rather than narrowing it — one
click, one condition, and a second click gets you back. (It is the grid's own
filter, the one setFilter holds; the filter row and the header menus filter
separately and keep applying.)
Several categories at once
Hold Ctrl (Cmd on a Mac) and click: that category joins the selection, and the grid shows the rows of any picked category. Ctrl-click a picked one to take it out again; the last one out clears the filter. On the grid it is one condition per category under an OR:
controller.getFilter();
// { logic: 'or', nodes: [
// { columnId: 'region', operator: '=', value: 'North' },
// { columnId: 'region', operator: '=', value: 'East' },
// ] }
As with one category, the chart keeps every category on screen, the picked ones at full strength and the rest faint; the note reads "The grid is filtered to North or East." To do that it reads the view without its own filter — the column filters, the quick search and an external filter still apply. A plain click goes back to one category.
A click on the chart's background clears what the chart put on the grid, however it was picked. A filter that is not the chart's (typed in the filter row, set by your code) is left alone.
From the keyboard, the chart is one tab stop: Tab to it, and the arrow keys (or Home / End) move a focused category. A chip at the top of the chart names it with its values and position ("North: Revenue 20 — 2 of 4"), its bars are outlined, and the chip is a live region, so a screen reader says the same. Enter or Space does what a click does, Ctrl (Cmd on a Mac) adds like a Ctrl-click, and pressing it again on a picked category takes it out. On a zoomed chart the view follows the focus; +, − and 0 still zoom. A click moves the keyboard's focus to the bar it hit. In React the outline is drawn on bars and slices; on a line or area the chip alone shows the focus.
Charts filtering each other
Every chart that reads the view (source: 'view', the default) follows the
grid, so a cross-filter set from one chart narrows all the others. Open a
second chart window by month and click a region in the first: the second
redraws for that region's rows; Ctrl-pick three regions and it shows those
three. A click in the second chart replaces the first chart's pick rather
than narrowing it further, since there is one grid filter — the first chart
then follows the grid like any other.
Zoom and pan
Once an axis is bucketed it can legitimately hold hundreds of points, so the panel lets you look closer:
| Scroll over the chart | zoom in and out, around the pointer |
| Drag | pan (only while zoomed) |
| ← → | pan by a quarter of the window |
| + − | zoom from the centre |
| 0 or Home | show everything |
While a window is active the panel says "Showing 295 of 900" with a Show all beside it.
This is a slice of the model, not a transform of the picture and not a
library feature. The chart engine hands the renderer a smaller ChartModel;
nothing is recomputed, and the series are subarray views over the same
buffers, so panning allocates nothing. That also means a renderer you register
yourself gets zooming without writing any:
chartRegistry.register({
def: { id: 'radar', label: 'Radar', requiresCategory: true, windowable: true },
render: (model, ctx) => <MyRadar model={model} colors={ctx.colors} />,
});
windowable is off by default, and deliberately false for pie and
donut: a pie states "these are the parts of a whole", and a pie of 30 slices
out of 900 categories states something untrue. Zooming is offered only where it
does not lie.
A drag that ends on a bar does not cross-filter — the two gestures are kept apart, so panning cannot filter the grid by accident.
Performance
Aggregation runs off the main thread whenever the grid's worker is in play (20.000 rows by default), reusing the columns the worker already encoded for filtering and sorting. Measured on a million rows, two series:
| Main thread | Worker | |
|---|---|---|
| Aggregate | 111,7 ms | 33,0 ms |
What crosses the worker boundary is categories × series numbers — 90 floats for
a 30-category, 3-series chart — not the rows.
Two rules keep it cheap while you use the grid:
- A sort does not recompute the chart. Aggregation is order-independent, so reordering a million rows costs the chart nothing.
- Changing chart type does not recompute either — the model is reused and only the renderer changes.
A filter, a search, or a data change does recompute; those are the things that change the numbers.
aggregate: 'custom'takes a reducer function, and a function cannot be sent to a worker. A spec using one is computed on the main thread.
Messages in the plot
The canvas says what it is doing instead of showing an empty frame:
| Message | When |
|---|---|
| Nothing to chart yet. | The chart's rows hold nothing to chart. |
| No visible series. | Every series is switched off in the legend. The legend stays, to switch one back on. |
| Loading… | The chart is still being computed — the first open on a large grid, a new column or grouping, the first click of a Ctrl selection. |
"Loading…" waits 300 ms before it shows, so the answers that land at once — nearly all of them — never flash a message. It lies over the plot rather than replacing it: a slow recompute keeps the previous chart readable under it until the new one arrives. Before the first answer the canvas is blank, never "Nothing to chart yet." — a chart that announces there is no data and then fills with bars reads as broken. A recompute the grid starts on its own (a filter, an edit) keeps the previous chart up without a message, as it always did.
All three are status regions (role="status"), so a screen reader hears what
the eye sees. They come translated in all twelve languages; rename them with
charting.labels — empty, noVisibleSeries and loading in React,
chartEmpty, chartNoVisibleSeries and chartLoading in JavaScript.
The model without the panel (Community)
If you would rather draw the chart yourself, take the data and stop there:
import { useGridChartData } from '@kanunilabs/datagrid-react';
const spec = useMemo(
() => ({ categoryColumnId: 'region', series: [{ columnId: 'revenue', aggregate: 'sum' }] }),
[],
);
const model = useGridChartData(controller, spec);
Memoize the spec — a new object reference recomputes. The hook subscribes to the grid and returns:
interface ChartModel {
categories: string[]; // '' for blanks, matching the checkbox filter
series: Array<{
label: string;
columnId: string;
aggregate: SummaryType;
values: Float64Array; // one per category; NaN = nothing to total
}>;
truncated: boolean; // categories were collapsed or dropped
otherIndex: number | null; // where "Other" sits, if present
rowCount: number;
categoryCount: number;
rankingExact: boolean; // false past the distinct-category ceiling
// Only on a bucketed axis:
bucket?: { kind: 'date' | 'number'; unit?: ChartDateUnit; size?: number; adjusted: boolean };
bucketStarts?: Float64Array; // inclusive lower bound per category
bucketEnds?: Float64Array; // exclusive upper bound; dates are ms
}
NaN rather than 0 is deliberate: "no numeric values here" and "totals to
zero" are different answers, and a zero-height bar claims the second.
excludeFilter: true on the spec charts the view without the grid's own
filter (the one setFilter holds) while keeping the column filters, the
search and an external filter — what the panel does while several categories
are picked, so a chart of your own can cross-filter the same way.
A floating window
Pop out in the panel's toolbar lifts the panel off its dock and lays it over the grid as a window. It is the same panel, so the chart keeps its type, its series, the legend switches and the zoom. Dock puts it back.
- Drag the title bar to move it; drag the bottom-right corner to resize it. The controls in the bar keep their own clicks.
- From the keyboard: the grip at the start of the bar moves the window with the arrow keys, the corner grip resizes it (10px a press, 50px with Shift).
- The window always stays inside the grid. Dragged past an edge it stops at the edge, and a grid that shrinks pulls the window back in.
- Fullscreen from a window and back returns to the window where it was.
To open as a window, set floating: true for a centred one, or give the
rectangle: floating: { x: 40, y: 24, width: 640, height: 360 } — px, relative
to the grid, top-left corner first. The plain-JavaScript grid takes the same
option.
Where the window is belongs to the chart state: getState() has
floating: { x, y, width, height } while it floats and no floating key while
it is docked, so a docked panel's state reads exactly as it did before. The saved
view keeps it, and setState with a state that has no rectangle docks the
panel. A move or a resize is reported once, when it ends, as a chartChanged
with changes: ['placement'].
In a container of your own
container puts the chart somewhere else on the page — a dashboard tile, a
side panel — instead of docking it above the grid:
const [box, setBox] = useState<HTMLDivElement | null>(null);
<div ref={setBox} className="chart-tile" style={{ height: 420 }} />
<EnterpriseDataGrid charting={{ container: box }} /* … */ />
Everything that opens the chart opens it there: the toolbar button, the menus
and the API. Pop out and extra windows float inside the container. The
panel sits in a box that carries the grid's theme classes, so a dark grid's
chart is dark in the tile as well. In React a container that is still null (a
ref not attached yet) docks the chart as usual until it exists; in JavaScript
pass the element itself, charting: { container: tile }, and destroying the
grid removes the box from it.
Several charts at once
New window opens a copy of the chart in a window of its own, floating over the grid. From then on the two are independent: change the type, the columns or the format of one and the other stays as it was. A copy of the docked panel opens centred over the grid; a copy made from a window opens a step down and to the right of it, so a row of copies fans out instead of piling up. Windows cannot dock — the dock is the panel's — and Close on a window removes it.
The windows are numbered in their title ("Chart 2", "Chart 3"…) after their
id, the same id their events carry (below). From code:
const win = chart.openWindow({ type: 'pie' }); // a copy of the panel's chart, as a pie
chart.openWindow({ floating: { x: 20, y: 20, width: 420, height: 300 } }); // exactly there
chart.getWindows(); // the windows open now, oldest first
win.update({ format: { title: 'Share' } });
win.getState(); // a GridChartState, like the panel's
win.close();
Fullscreen and a fixed height
height sets the docked height; fullscreen ignores it and fills the screen.
The height is a number rather than "fill" for a reason worth knowing: recharts
sizes itself from a ResizeObserver, which never fires while an element is
display: none. A chart inside a collapsed accordion or an inactive tab would
stay blank until it is shown. A fixed height sidesteps the observer entirely.
Image export
The panel has PNG and SVG buttons. The file is named after what the
chart shows — region-revenue.png, not chart.png.
Both go through the same step, which is the part worth knowing about: the SVG in the page is not self-contained. Every colour in it reads a CSS custom property that resolves against the document, and the text inherits a font from an ancestor. Serialised naively it would open as the fallback palette in the browser's default serif. So the export flattens the clone first — the values the browser actually computed are written onto each element — and adds an opaque background, because a transparent PNG dropped on a dark slide loses every dark label on it.
PNG is rasterised at 2× by default; a chart exported at CSS pixels looks soft the moment it lands in a document.
Call them directly if you would rather not use the buttons:
import { exportChartPng, exportChartSvg } from '@kanunilabs/datagrid-react-enterprise';
const svg = container.querySelector('svg');
await exportChartPng(svg, { fileName: 'sales-by-region', pixelRatio: 3 });
exportChartSvg(svg, { background: null }); // keep transparency deliberately
JPEG, a size of your choosing, or the image as data
The chart API (below) takes a format and a size, and can hand the image back
instead of downloading it — to keep beside a saved report, send to a server or
put in an <img>:
await chart.current?.download({ format: 'jpeg', width: 1200 }); // .jpg, 1200 px wide
const url = await chart.current?.getImageDataUrl({ width: 800, height: 600 }); // data:image/png;base64,…
format is 'png' (default), 'jpeg' or 'svg'. One side keeps the chart's
proportions; both fix the box and centre the chart in it on its background —
stretched to fit, every label would be distorted. The chart is vector, so any
size is sharp. JPEG has no transparency, so background: null is drawn white
there. Both calls answer null / false while the panel is closed. The same
options work on the bare exporters: chartImageDataUrl(svg, options),
exportChartJpeg, exportChartImage(svg, { type }).
Chart API, events and saved charts
The chart is plain data, a GridChartState: whether the panel is open, the
type, the category and series columns, the grouping, which rows it reads, the
bubble's size column, the stacking, the Format choices, the series switched off
in the legend and the zoom window. Both grids hand out the same shape and take
it back, so a chart saved by the React grid restores in the JavaScript one.
In React, pass a ref:
import type { GridChartApi } from '@kanunilabs/datagrid-core';
const chart = useRef<GridChartApi | null>(null);
<EnterpriseDataGrid charting={{ apiRef: chart }} /* … */ />
chart.current?.open({
categoryColumnId: 'region',
series: [{ columnId: 'revenue', aggregate: 'sum' }],
type: 'line',
});
chart.current?.open({ format: { title: 'Q3' } }); // open already: the title changes, the rest stays
const saved = chart.current?.getState(); // JSON-safe
chart.current?.setState(saved); // later, or in another grid
chart.current?.close();
In JavaScript the same object is grid.chartPanel:
grid.chartPanel.open({ type: 'bar', stacking: 'stacked' });
const saved = grid.chartPanel.getState();
grid.chartPanel.setState(saved);
open(seed) takes any part of the state, and what it leaves out keeps its
value. Reopening a closed panel shows the chart the reader left, with every
series shown and the axis unzoomed. setState drops what the grid no longer
has instead of refusing the whole chart: a series over a removed column goes,
and an unknown category falls back to the panel's default.
Events
The controller's event bus reports the panel:
controller.events.on('chartOpened', ({ state }) => {});
controller.events.on('chartChanged', ({ state, changes }) => {});
controller.events.on('chartClosed', ({ state }) => {});
changes names what moved: type, data, stacking, format,
hiddenSeries, window or placement (docked or floating, or the window
moved). An extra chart window reports the same three events with its chartId
('chart-2'…); the panel's own events have no chartId. data is a change of columns, reducers, grouping
or row source — the parts that run the aggregation again. A pan is reported
once, when the pointer is released, not on every move. Changes made through the
API while the panel is closed send no event; they arrive with the next
chartOpened.
In the saved view
The chart is part of controller.getViewState(), under parts.chart.
applyViewState restores it, and stateStoring keeps it with no code of
yours: change the chart, reload the page, and it comes back. Extra windows
travel with it, under parts.chart.windows — each a chart state with its id
and its rectangle — and a view without them closes the ones that are open.
Sparklines
A chart small enough to live in a cell. Not part of the chart panel — it is a property on the column, and it draws whatever array the cell holds:
const columns = [
{ field: 'name', headerName: 'Product' },
{
field: 'weekly', // e.g. [12, 18, 9, 22, 31, 28]
headerName: 'Last 6 weeks',
width: 140,
sparkline: { type: 'line' },
},
];
| Option | Type | Default |
|---|---|---|
type | 'line' | 'area' | 'bar' | 'horizontalBar' | 'line' |
xKey / yKey | string | 'x' / 'y' |
min / max | number | the series' own range |
showLast | boolean | on, except for the bar types |
showBaseline | boolean | on for the bar types, off otherwise |
highlight | { first?, min?, max? } | none |
color / negativeColor | CSS colour | the theme's primary / danger |
tooltip | boolean | off |
lineWidth / lineDashed | number (1–6 px) / boolean | the stylesheet's |
fillOpacity | number (0.05–1) | the stylesheet's |
markers | boolean — a dot on every reading | off |
labels | boolean — each bar's value beside it | off |
valueFormat | Intl.NumberFormatOptions | the locale's numbers |
pointColor | (point) => colour | undefined | none |
tooltipText | (point) => string | the value |
horizontalBar draws one row per reading, top to bottom, each bar growing to
the right from a vertical zero line — the shape for "how big is each part"
rather than "where is it heading".
What the cell can hold
Three shapes, and a column may use whichever its data already has:
[12, 18, 9, 22] // plain numbers
[['Q1', 12], ['Q2', 18], ['Q3', 9]] // [x, y] pairs
[{ day: '2026-06-01', sales: 12 }, /* … */] // objects: set xKey: 'day', yKey: 'sales'
Objects are read through xKey and yKey, which default to x and y.
When every reading has a number or a date as its x — a Date, or an ISO
date such as '2026-06-01' — the readings are sorted by it, and a line or area
places them by it: readings on the 1st, 2nd and 30th of a month sit close
together at the left and far apart at the right, as they did in time. Bars keep
one even slot per reading, in that sorted order. If any reading has no x, or a
text x such as 'Q1', the readings stay evenly spaced in the order given.
With tooltip on, a reading with an x shows it before the value
(6/30/2026: 31, Q3: 9); a bare ISO date is read as a calendar day, so it
never shows the day before in a time zone behind UTC. A reading without a y, or
with a y that is not a number, is a hole like any other.
Highlights and scale
highlight marks the first, lowest and highest readings: dots on a line or
area (highest green, lowest red, first muted), recoloured bars on a bar
sparkline. tooltip shows each reading's value on hover with the browser's own
tooltip, so it needs no script.
By default every cell scales to its own series, so a row peaking at 30 and a
row peaking at 3,000 look identical. Set min and max when the point is to
compare rows against each other.
showBaseline draws the zero line only when the series actually crosses zero —
a baseline at the floor of an all-positive series is just a second border. Bars
follow the same rule and grow from zero when zero is on the scale, from the
floor when it is not: a bar chart of values between 90 and 100 growing from zero
would be ten identical full-height bars.
Colours come from CSS classes (.kanuni-datagrid-sparkline-line,
-area, -bar, -bar--negative, -baseline, -last, -hi--first,
-hi--min, -hi--max, -lone, -marker, -ring, -label,
-label--inside), so themes and dark mode work with no JavaScript and nothing
recomputes when the theme changes. color and negativeColor set one column's
colours without a stylesheet.
Every dot on a line (-last, -hi--*, -lone, -marker) is coloured by its
stroke, not its fill: it is drawn as a round stroke so it stays round in a
drawing stretched to the cell, and stroke-width is its diameter. The last and
highlighted dots sit on a ring of the surface colour (-ring). Bars keep
fill, so a highlight class recolours a bar by fill and a dot by stroke:
.kanuni-datagrid-sparkline-last { stroke: #7c3aed; stroke-width: 6px; }
rect.kanuni-datagrid-sparkline-hi--max { fill: #15803d; }
path.kanuni-datagrid-sparkline-hi--max { stroke: #15803d; }
Lines, markers, labels and colours of your own
lineWidth, lineDashed and fillOpacity restyle one column's line and area;
a value out of range is ignored, not clamped, and the stylesheet keeps what you
leave out. markers puts a dot on every reading of a line or area, and each
dot carries the tooltip.
labels writes each bar's value beside it: past the end of a horizontal bar,
above a vertical one, or inside near the end when the bar reaches the far edge
and there is no room outside. The labels are page text laid over the drawing —
the drawing stretches to the cell, and text inside it would stretch with it.
valueFormat sets how the values print, in the labels, the tooltip and the
screen-reader summary alike.
pointColor colours each reading your own way. It is told the reading's value,
its position, its x when it has one, whether it is the first, last, lowest or
highest, and the row — and returns a colour, or nothing for the default. It
wins over highlight, color and negativeColor, and applies to bars and
dots (a line has one colour). tooltipText writes the tooltip from the same
facts, so it can show another column of the row beside the value; setting it
turns tooltips on.
A progress bar is a horizontal bar with one reading:
{
field: 'done', // 0.62
headerName: 'Progress',
valueGetter: (row) => [row.done], // the sparkline reads an array
sparkline: {
type: 'horizontalBar',
min: 0,
max: 1,
labels: true,
valueFormat: { style: 'percent' }, // "62%"
pointColor: ({ value }) => (value < 0.3 ? '#dc2626' : value < 0.7 ? '#d97706' : '#16a34a'),
tooltipText: ({ value, row }) => `${row?.task}: ${Math.round(value * 100)}% done`, // no row outside a grid
},
}
The maths is Community and has no DOM in it — useful if you want the paths without the grid:
import { sparklineGeometry, SPARK_WIDTH, SPARK_HEIGHT } from '@kanunilabs/datagrid-core';
const { line, area, bars, baselineY, last, count, points, min: low, max: high } =
sparklineGeometry(values, { min, max });
Only the drawing is Enterprise: <Sparkline> in
@kanunilabs/datagrid-react-enterprise, renderSparkline() in
@kanunilabs/datagrid-enterprise. With labels on a bar type,
renderSparkline() returns a <span class="kanuni-datagrid-sparkline-box">
holding the drawing and its labels; otherwise the <svg> itself.
What sparklines do not do
- A non-numeric entry is a gap, not a zero. A
nullfrom a join or a missing period keeps its place in the series: the line breaks there and the bar's slot stays empty, instead of a dip that never happened. A reading with a gap on both sides gets a dot, because no line reaches it. Only numbers and non-empty numeric strings are plotted. - Nothing numeric means nothing drawn. The cell falls through to the grid's ordinary text rendering.
- A flat series draws through the middle — one value, or every value equal, has no range to scale against. A single point sits at the left edge, so a series that grows to two points keeps its first point in place.
- No click target.
tooltipgives a hover readout; there is no click event. The SVG isrole="img", labelled in the grid's language with the count, the range and the last value (ariaLabelreplaces it). - Sorting and filtering are not meaningful on the column. With no
dataTypethe engine collatesString(value), so[1,2,3]sorts as the text"1,2,3". Give the column acomparator(sort by the last reading, say) or turn sorting off. - Enterprise only for the drawing. Community can compute the geometry and render it itself; the components ship in the paid packages.
Not yet
- The chart aggregates data rows; grid grouping is not carried into it. The chart's category axis is its own group-by, and stacking the grid's grouping on top would leave two competing answers to "what is grouped here".