developer guide
Statistics and capability: JavaScript Data Grid Guide
What the grid knows about its own numbers: column profiling, process control and capability, confidence intervals, the tiles that put a figure above the table, and a summary that counts and filters the rows that look wrong.
Developer guide › Statistics and capability
Profiling and statistics
grid.statistics answers questions about the rows the filters left, so every
figure describes what the user is looking at rather than the whole table.
Everything worth knowing about a column, in one pass
const { createHeadlessGrid } = await import('../packages/core/src/index.js');
const grid = createHeadlessGrid({
rowKey: 'id',
columns: [{ field: 'id', type: 'number' }, { field: 'capacity', type: 'number' }],
rows: [
{ id: 1, capacity: 10 }, { id: 2, capacity: 20 }, { id: 3, capacity: 30 }, { id: 4, capacity: 40 }, { id: 5, capacity: 60 },
],
});
const p = grid.statistics.profile('capacity');
// The real ColumnProfile fields: rows, present, missing, distinct, min, q1,
// median, q3, max, mean, stddev, outliers, histogram.
const out = [p.rows, p.present, p.missing, p.distinct, p.min, p.q1, p.median, p.q3, p.max, p.mean, p.stddev.toFixed(1), p.outliers, p.histogram.length];
grid.destroy();
return out.join('|');
One pass over the filtered rows, so every figure agrees with the others and with the totals
row. rows and present say how much of the column is there to read,
the quartiles and stddev describe its spread, outliers counts by the
interquartile rule and histogram is the bins, ready to draw.
The profile of a column the grid does not hold, computed by the source
const { createHeadlessGrid, createPushdownSource } = await import('../packages/core/src/index.js');
const rows = Array.from({ length: 100 }, (_, i) => ({ id: i, price: i + 1 }));
const adapter = {
name: 'demo',
capabilities: { filter: 'tree', operators: ['equals'], range: true, total: true },
async execute(q) { return { rows: rows.slice(q.range.start, q.range.end), total: rows.length }; },
async executeAggregates(q, aggs) {
const by = { count: 100, countValues: 100, distinct: 100, min: 1, max: 100, avg: 50.5, median: 50.5, p25: 25.75, p75: 75.25, stddev: 29.01 };
return Object.fromEntries(aggs.map((a) => [a.id, by[a.fn]]));
},
};
const grid = createHeadlessGrid({
rowKey: 'id',
columns: [{ field: 'id', type: 'number' }, { field: 'price', type: 'number', facet: { buckets: 5 } }],
source: createPushdownSource({ adapter, pageSize: 50, aggregates: { default: 'engine' } }),
});
const held = grid.statistics.profile('price') === null; // true: the grid holds no rows to read
const p = await grid.statistics.profileAsync('price'); // the engine's answer
const named = p.unavailable.map((u) => u.stat).join('+'); // what it could not push down
const buckets = grid.columns.get('price').facet.buckets; // a column's own facet settings
grid.destroy();
return [held, p.computed, p.rows, p.median, named, buckets].join('|');
| Method | Answers |
|---|---|
| reduce | A column through any of the thirty-eight named kernels, or one of your own. |
| profileAsync | grid.statistics.profileAsync(colId): the same profile when the grid does not hold the rows. Over a pushdown source without fullDataset the source's engine computes the count, distinct count, min, max, mean, quartiles, median and standard deviation the adapter supports, over the grid's filters; a figure it could not push down is named under unavailable with the reason rather than left blank. It is never a Web Worker - that pushdown call is the only case that leaves the main thread, and everywhere else it is profile(), resolved on the main thread. |
| correlation | Pearson's r between two columns. spearman resists an outlier; kendall is tau-b. |
| regression | A least-squares fit of one column on another, with slope, intercept and r². |
| weightedAverage | One column averaged by another. weightedQuantile for the median and beyond. |
| series | How a column varies along an ordering. by is required and never guessed. maxDrawdownFrom/maxDrawdownTo are 0-based positions into the ordered filtered rows - not dates - and the matching maxDrawdownFromAt/maxDrawdownToAt carry the ordering axis at those positions. |
| shadow | What the grid knows about a row over time: updates, delta, rate, rank, percentile, streak. |
| bayes | A Bayesian estimate for a rate: grid.statistics.bayes(colId) reads a binary measure and returns each group's successes, trials, Beta-Binomial posterior and equal-tailed credible interval, with the probability one group's rate is higher when split by a column. |
The filters are part of the question. Every one of these reads the filtered rows. Narrow the grid and the statistics narrow with it, which is the behaviour you want when the filter is the analysis.
Kernels see arrival order, not display order. Anything order-dependent
takes an explicit by rather than inferring one from the current sort, so the
answer does not change when a user clicks a column header.
Compare groups
grid.statistics.compare turns the comparison question into one call: split the
filtered rows by one column, measure another, and get the test, the p-value, the interval
and the effect size - plus a one-sentence verdict that says it in words.
A test chosen by the data, with the reason named
const r = grid.statistics.compare({ measure: 'hours', by: 'group' });
r.test; // 'welch', 'anova', 'chiSquare', … - or 't', 'mannWhitney', 'kruskal', 'proportions'
r.chosenBy; // 'auto', and r.reason says why this test over the others
r.pValue; // the datum to interpret; there is no `significant` flag
r.interval; // { estimate, lower, upper, method } on the difference
r.effectSize; // { name, value, label } - Cohen's d, Cliff's delta, Cramer's V or eta squared
r.reliable; // false when a compared group stands on fewer than ten rows
r.verdict; // "Hours is higher for b than for a by about 10; the difference is unlikely to be chance (p < 0.001) and the effect is large."
test: 'auto' is the default and picks from the data: two numeric groups use
Welch's t (unequal variances not assumed), or Mann-Whitney U when a group
is non-normal - the pooled Student's t runs only when forced with test: 't';
three or more numeric groups use ANOVA or Kruskal-Wallis; a categorical measure a
two-proportion z or chi-square. Force the test with test when the question
fixes it. paired names a key column to match the two groups as pairs. A group
with fewer than three readings, or with zero variance, is refused with a warning - the grid
will not hand back a p-value computed from a sample too small or too flat to carry one.
Two group-comparison calls, one test each: compare and
compareGroups agree on the two-group numeric case (Welch by default, the same
p-value, interval and effect size, and the same one-sentence verdict). They differ in how
they treat more than two groups. compareGroups is always a two-group test:
with three or more groups and none named, it compares the two most frequent and says which
in its groups. compare runs the multi-group test instead - ANOVA
or Kruskal-Wallis over every group - and its groups lists them all;
the Compare groups panel prints that list under "Groups compared" so a multi-group verdict
is never mistaken for a two-group one.
On a binary measure with two groups the result also carries bayesian - the same
Beta-Binomial estimate statistics.bayes reports: each group's posterior rate with
its equal-tailed credible interval, and the probability the second group's rate is higher. The
Compare groups panel prints it under its own "Bayesian estimate (uniform prior)" heading after
the existing figures, in words that can never be read as the p-value beside it. Set
toolPanel: { panels: [{ name: 'compareGroups', props: { bayesian: false } }] } to
hide that section; it is on by default. Any other measure or group count shows no section and
no empty heading.
A categorical or binary measure is compared as a rate, and every reading names the value it
counts - the verdict sentence, the Bayesian rate rows and the result's
category - so a yes/no measure reads "Yes rate is higher for b than for a…",
never a bare "rate". Which value is counted never depends on row order, sorting or filtering:
a boolean column, or a column holding exactly one clear affirmative pair (true/false, yes/no,
1/0, any letter case), is counted on its affirmative member, and any other pair - red/blue,
for example - uses the one stable rule that the value whose string form sorts first by code
point is counted. To name the counted value yourself, pass category; a value the
measured column does not hold is refused with a one-time [lattice] warning and a
null result, never a rate of zero built from nothing.
No multiple-comparison correction. Each statistics.compare
call is one test at its declared alpha. Running it across many pairs of groups - every category against every other - inflates the family-wise error rate exactly as a run of
unadjusted t-tests does; if you sweep the groups, correct for the sweep yourself.
Observational, not causal. The verdict describes an observed difference in the rows the filters left. The grid has no experimental design, no randomisation and no confounders, so it cannot say why the groups differ - only that they do, and by how much.
The effect-size label is a band, not a rule. "Large" is a conventional threshold on Cohen's d, Cliff's delta, Cramer's V or eta squared, chosen so the words mean the same thing across tests. A result at the boundary of two labels is the same number either way.
Process control and capability
Whether a process sits inside the tolerance it was given, and whether it is behaving or drifting. The tolerance is declared once, on the column.
Full guide: Process control and capability ›
Confidence intervals
How firmly the data pins a figure down. An interval narrows as the grid does, because it describes the filtered rows and not the whole table.
Full guide: Confidence intervals ›
Statistic tiles
A headline figure over a grid, with the change since a baseline, a tone from thresholds, and the interval underneath.
Meters and tile bars
createMeter(el, config) draws one horizontal bar: a value in a range, an optional
target mark, colour bands, status segments, a caption such as 3 of 8 and an
indeterminate state. It is the bar a dashboard otherwise builds by hand. Pass
container in the config; give it a grid and the value comes from an
aggregate over the rows the grid shows, so the bar follows the grid's filters like a
createStat tile. Colours are theme tokens, so the bar follows light and dark.
The element is role="meter" with aria-valuenow,
aria-valuemin, aria-valuemax and an aria-valuetext
carrying the caption, the target and any band or segment label; an indeterminate meter is a
progressbar with no value. Give it a label or an
ariaLabel, which is its accessible name.
| Option | Type | Description |
|---|---|---|
| container | Element | string | Required. Where the meter is drawn. |
| grid | Grid | Read the value from this grid and follow its filters. |
| value | number | spec | fn | A literal, a { of, fn } reduction, or a function of the grid. of and fn may also sit on the config. |
| min | number | The value at an empty bar. 0 by default. |
| max | number | The value at a full bar. 100 by default. |
| target | number | fn | Draws a mark at this value. |
| tone | MeterTone | The fill's colour below every band: neutral, info (default), success, warning, danger or accent. |
| bands | MeterBand[] | [{ from, tone, label }]: from from up the fill takes tone; the highest band reached wins. |
| segments | MeterSegment[] | fn | [{ value, tone, label }] drawn in order instead of one fill; the value is their sum. |
| label | string | Text above the bar and its accessible name. |
| ariaLabel | string | An accessible name that differs from label. |
| caption | string | fn | Text under the bar, such as 3 of 8. |
| format | fn | Formats the value text. |
| showValue | boolean | Show the value text beside the label. true by default. |
| indeterminate | boolean | An unknown amount of progress. |
| live | boolean | false stops it following the grid; refresh() still works. |
The handle has element(), value(), refresh(),
update(options) and destroy(). A KPI tile gains the same bar:
createStat and the grid's kpis strip take target and
bar. bar: true (or 'under') draws the value against the
target beneath the number; 'instead' draws it in the number's place; an object
sets position, min, max, bands,
tone and caption. With no max the bar spans 0 to the
target, so a full bar is a met target.
A target bar, a status-segmented bar and a tile bar
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createMeter, createStat } = await import('../packages/dom/src/index.js');
const dom = createTestDom({ width: 400, height: 200 });
// 30 of 100, with a mark at the 80 target.
const meter = createMeter({
container: dom.root, label: 'Capacity', value: 30, min: 0, max: 100, target: 80, caption: '3 of 8',
tone: 'info', bands: [{ from: 90, tone: 'danger' }], showValue: true, live: false,
empty: ' - ', class: 'capacity', format: (v) => String(v), ariaLabel: 'Capacity used',
});
const root = meter.element();
const bar = root.querySelector('.lat-meter__fill').style.width;
const mark = root.querySelector('.lat-meter__target').style.insetInlineStart;
// A done / in progress / blocked bar: the value is the segments' sum.
const sprint = createMeter({
container: dom.root, label: 'Sprint', max: 10,
segments: [{ value: 4, tone: 'success', label: 'Done' }, { value: 2, tone: 'info', label: 'In progress' }, { value: 1, tone: 'danger', label: 'Blocked' }],
});
// An indeterminate meter is a progressbar with no value.
const busy = createMeter({ container: dom.root, label: 'Loading', indeterminate: true });
// A KPI tile showing 60 against a target of 80.
const tile = createStat({
container: dom.root, title: 'Revenue', value: 60, target: 80,
bar: { position: 'under', min: 0, max: 80, tone: 'success', caption: 'of 80' },
});
const tileBar = tile.element().querySelector('.lat-meter__fill').style.width;
const out = `bar ${bar} | mark ${mark} | role ${root.getAttribute('role')} | segments ${sprint.value()} | tile ${tileBar}`;
meter.destroy(); sprint.destroy(); busy.destroy(); tile.destroy();
return out;
Anomaly summary chip
Give a column an anomalyFlag shadow () and turn on
anomalySummary, and the grid shows a small chip reading how many rows that column
flags. Click it to filter the grid to exactly those rows; click again to clear.
Full guide: Anomaly summary chip ›
Explaining a number
grid.explain breaks a column's total over the filtered rows into ranked
contributors - the rows themselves, or the groups of a dimension you name - so
“why is this total what it is” gets an answer, not just a number.
Who drives the total, and who drove its change
const { createHeadlessGrid } = await import('../packages/core/src/index.js');
const grid = createHeadlessGrid({
rowKey: 'id',
columns: [
{ field: 'id', type: 'number' },
{ field: 'region' },
{ field: 'quarter' },
{ field: 'amount', type: 'number', total: 'sum' },
],
rows: [
{ id: 1, region: 'North', quarter: 'Q1', amount: 100 },
{ id: 2, region: 'North', quarter: 'Q2', amount: 200 },
{ id: 3, region: 'South', quarter: 'Q1', amount: 50 },
{ id: 4, region: 'South', quarter: 'Q2', amount: 150 },
],
});
const r = grid.explain({ column: 'amount', group: 'region' });
const c = grid.explain({ column: 'amount', group: 'region', compare: { col: 'quarter', op: 'eq', value: 'Q2' } });
const who = r.contributors.map((x) => `${x.label}:${x.contribution}`).join(' ');
const why = c.compare.drivers.map((d) => `${d.label}:${d.effect}`).join(' ');
grid.destroy();
return `${r.total} | ${who} | ${c.compare.before} to ${c.compare.after} | ${why}`;
The arithmetic is the grid's own - the same total kernels the totals row
uses, over the same filtered rows statistics.reduce reads - so an
explanation and the number it explains cannot disagree. sum, count
and countValues add up: a contributor's contribution is its own
value and share is that over the total. avg is not additive, so a
contributor's contribution is its weighted effect and the result says so with
weighted: true; min and max have one contributor and
say single: true. With compare the change is decomposed into
drivers marked new, dropped or changed, ranked by
effect. Every result also carries explanation: the plain-language sentence
the Explain panel writes - who accounts for the most, and the runner-up - localised through the same catalogue the panel uses, so the field and the panel can never
differ. When compare was given, that sentence is the change's, and it also
rides on compare.explanation. Over a pivoted pushdown grid it returns
null - a pivot's terminal
groups carry no leaf rows client-side - while on a memory source pivoting is
presentation over rows the grid still holds, so explain reads them normally.
A Bayesian rate estimate
grid.statistics.bayes answers "how likely is the rate, and how sure are we" with
a Beta-Binomial posterior: start from a Beta prior, count the successes in the trials, and
report the posterior mean and the equal-tailed credible interval that holds the middle
level of the posterior's mass. The measured column must be binary. The counted
value - reported as category, and named in the Compare groups panel's rate rows
and probability sentence - never depends on row order, sorting or filtering: a boolean column
or a clear affirmative pair (true/false, yes/no, 1/0, any letter case) is counted on its
affirmative member, and any other pair uses the one stable rule that the value whose string
form sorts first by code point is counted.
A rate per group, and the chance one group is higher
const { createHeadlessGrid } = await import('../packages/core/src/index.js');
const grid = createHeadlessGrid({
rowKey: 'id',
columns: [{ field: 'passed', type: 'boolean' }, { field: 'group', type: 'string' }],
rows: [
{ id: 0, passed: true, group: 'a' },
{ id: 1, passed: false, group: 'a' },
{ id: 2, passed: true, group: 'a' },
{ id: 3, passed: false, group: 'b' },
{ id: 4, passed: true, group: 'b' },
],
});
const r = grid.statistics.bayes('passed', { by: 'group' });
grid.destroy();
return `${r.category}|${r.groups[0].successes}/${r.groups[0].trials}|${r.groups[1].successes}/${r.groups[1].trials}|${r.probabilityHigher.toFixed(4)}`;
prior is 'uniform' (Beta(1, 1), the default), 'jeffreys'
(Beta(½, ½)), or { alpha, beta } with both positive; level defaults
to 0.95. Each group reports its successes, trials, posterior
alpha and beta, posterior mean, and the
lower/upper credible bounds. With exactly two groups
probabilityHigher is P(second group's rate > first's). To count a particular
value yourself, pass category; a value the column does not hold is refused with a
one-time [lattice] warning, as is a non-binary measure
or a prior that is not positive, rather than answered with a number built from nothing.