Lattice Grid

developer guide

Statistics: JavaScript Data Grid Guide

What the grid knows about its own numbers, and how they have moved since the page loaded.

Try it: Statistics on a live price book

Prices tick every second or so. The median in the totals row, the change and rank shadow columns and the profile underneath all follow the data; open the statistics panel on the left to see the full profile of any column.

Loading a live grid…

<link rel="stylesheet" href="https://cdn.latticegrid.dev/lattice-grid@1.133.1/lattice-grid.min.css">
<script src="https://cdn.latticegrid.dev/lattice-grid@1.133.1/lattice-grid.min.js"></script>

<div id="grid" style="height: 400px"></div>
<pre id="out" style="margin-top: 12px; min-height: 5.5em"></pre>

<script>
  const rows = [
    { symbol: 'ALDR', name: 'Alder Systems', price: 118.4, volume: 1840000 },
    { symbol: 'BRCH', name: 'Birch Logistics', price: 42.15, volume: 920000 },
    { symbol: 'CEDR', name: 'Cedar Foods', price: 67.8, volume: 1210000 },
    { symbol: 'DOGW', name: 'Dogwood Energy', price: 23.9, volume: 3480000 },
    { symbol: 'ELMR', name: 'Elmer Biotech', price: 156.25, volume: 640000 },
    { symbol: 'FRNW', name: 'Fernwood Retail', price: 31.6, volume: 2100000 },
    { symbol: 'GLDN', name: 'Golden Rail', price: 88.05, volume: 760000 },
    { symbol: 'HZLN', name: 'Hazelnut Media', price: 54.7, volume: 1530000 },
    { symbol: 'IVYC', name: 'Ivy Capital', price: 201.3, volume: 410000 },
    { symbol: 'JNPR', name: 'Juniper Water', price: 36.45, volume: 1980000 },
    { symbol: 'KLPT', name: 'Kelp Materials', price: 72.9, volume: 870000 },
    { symbol: 'LRCH', name: 'Larch Telecom', price: 95.6, volume: 1340000 },
  ];

  const config = {
    rowKey: 'symbol',
    grandTotalRow: 'bottom',
    toolPanel: { side: 'left', panels: ['columns', 'statistics'] },
    columns: [
      { field: 'symbol', title: 'Symbol', layout: { pin: 'start', width: 90 } },
      { field: 'name', title: 'Company', layout: { width: 150 } },
      { field: 'price', title: 'Price', type: 'number', format: { decimals: 2 }, total: 'median', layout: { width: 100 } },
      { id: 'moved', title: 'Change', shadow: { of: 'price', kind: 'delta' }, type: 'number',
        format: { decimals: 2, signed: true }, layout: { width: 100 } },
      { id: 'rank', title: 'Rank', shadow: { of: 'price', kind: 'rank' }, type: 'number', layout: { width: 80 } },
      { id: 'ticks', title: 'Ticks', shadow: { of: 'price', kind: 'updates' }, type: 'number', layout: { width: 80 } },
      { field: 'volume', title: 'Volume', type: 'number', format: { notation: 'compact' }, total: 'p95', layout: { width: 100 } },
    ],
    rows,
  };

  const grid = LatticeGrid.createGrid(document.getElementById('grid'), config);

  const report = () => {
    const p = grid.statistics.profile('price');
    const out = document.getElementById('out');
    if (out) {
      out.textContent =
        'price: ' + p.present + ' rows, median ' + p.median.toFixed(2) + ', q1 ' + p.q1.toFixed(2) +
        ', q3 ' + p.q3.toFixed(2) + ', mean ' + p.mean.toFixed(2) + ', stddev ' + p.stddev.toFixed(2);
    }
  };

  // A price moves a little every second, so the shadow columns have something to follow.
  let step = 0;
  const timer = setInterval(() => {
    const row = rows[(step * 5) % rows.length];
    const move = ((step % 7) - 3) * 0.35;
    row.price = Math.round((row.price + move) * 100) / 100;
    grid.rows.apply({ update: [{ symbol: row.symbol, price: row.price }] });
    step += 1;
    report();
  }, 1100);

  grid.on('destroy', () => clearInterval(timer));
  report();
</script>

Reductions in the totals row

Any numeric column can carry a statistical reduction in its total: total: 'median', 'p95', 'stddev', 'iqr' and more than twenty others. Every figure is computed over the filtered rows, and quantiles use the R type 7 definition, the same one NumPy computes by default and Excel's PERCENTILE.INC returns, so a median here matches the one a reviewer gets in their own spreadsheet. A deviation states whether it is the sample or the population form rather than leaving you to guess: the sample form is the default and the population form is available by name.

grid.statistics

The same figures, and the ones a column at a time cannot answer, are on grid.statistics: a full column profile, any single reduction, two-column figures like correlation and regression, and whole-series measures such as volatility and drawdown over a date-ordered column. It will also project a column forward: name the value and the column that carries its time axis, choose a straight-line or a seasonal fit and how far ahead to look, and get back the projected points and the fit quality, computed over the filtered rows so the projection reshapes as you narrow the grid.

Correlation returns nothing when a column never varies, rather than a confident number that means nothing, and it reports how many rows it was drawn from, because a figure over forty pairs is a different claim from one over a thousand.

grid.statistics.profile('margin');
// { rows, present, missing, distinct, min, max, mean, median,
//   q1, q3, iqr, stddev, outliers, histogram }

grid.statistics.reduce('margin', 'p95');       // any registered kernel
grid.statistics.correlation('spend', 'revenue'); // Pearson's r
grid.statistics.regression('spend', 'revenue');  // { slope, intercept, r2, n }
grid.statistics.series('price', { by: 'date' }); // volatility, drawdown, ...
grid.statistics.forecast('sales', { by: 'month', method: 'linear', horizon: 6 });
// the next steps projected ahead, each with its place on the time axis and a
// value, plus the fit quality, so you can see how well the line follows history

The statistics panel

The end-user half of profile() is a docked tool panel: a column picker, the twelve one-pass figures and a histogram of the column's shape, all following the filters. It also shows Shape (skewness, kurtosis, Jarque-Bera), Robust (trimmed and winsorized means, MAD), Concentration (Gini, HHI, entropy) and Capability where a column declares a spec. A section whose reductions all return null is left out rather than shown as a column of dashes.

toolPanel: { side: 'left', panels: ['columns', 'statistics'] }

Shadow columns

A shadow column is declared against another column and maintained by the grid. It has no field in the data, and it is not a computed column either, because its value depends on what happened before. It is a real column throughout: sortable, filterable, groupable, exportable, saveable into a view, which is what makes "every row repriced more than twice, most-changed first" one gesture.

columns: [
  { field: 'price', type: 'number' },
  { id: 'moved',  title: 'Change',  shadow: { of: 'price', kind: 'delta' } },
  { id: 'rank',   title: 'Rank',    shadow: { of: 'price', kind: 'rank' } },
  { id: 'movers', title: 'Places',  shadow: { of: 'price', kind: 'rankChange' } },
  { id: 'run',    title: 'Streak',  shadow: 'streak' }, // shorthand: the column beside it
]

The sixteen kinds

KindValue
updatesHow many times the value has changed. Arrival is not a change.
updatedAtWhen it last changed, as a Date.
sinceUpdateMilliseconds since it last changed.
deltaCurrent value minus the baseline.
deltaPercentThe same as a percentage; a change from nothing reads null.
rateChange per second, from the last two readings.
historyThe recent readings, oldest first; depth sets how many.
firstValueThe baseline itself.
streakConsecutive moves in one direction, signed; it resets on a turn.
rankCompetition rank, largest first; ties share the better rank.
rankAscThe same ranking from the other end.
rankChangePlaces climbed since the baseline; the "top movers" column.
percentileThe share of rows at or below this one, 0 to 100.
quartile1 to 4, agreeing with percentile.
zScoreDeviations from the mean; no spread reads null.
shareOfTotalThe value over the column's total, as a percentage.

Shadow columns follow the data live. As values arrive or change - a streaming price, an edit, a new row - the grid keeps every shadow current, so the change count climbs, the delta moves and the rank re-sorts in front of the user without a redraw of your own. A live trading book shows the whole set moving at once.

Positional kinds rank over every tracked row, not the filtered set, so "the top ten movers" does not depend on what happens to be on screen; pass scope: 'filtered' to rank within the filters instead. grid.statistics.rebase(col) is "mark all": it moves every baseline to now, so the deltas and the rank change start again from the current values.

Process capability

Declare a tolerance on a column and the capability figures, a control chart and any out-of-tolerance rule all read the same limits. Cp and Cpk use short-term variation; Pp and Ppk use the overall deviation, and the gap between them is the point: Cpk well above Ppk means the process drifted.

columns: [{ field: 'mm', type: 'number',
  spec: { lower: 9.5, upper: 10.8, target: 10 } }]

grid.statistics.capability('mm');
// { cp, cpk, pp, ppk, sigmaWithin, sigmaOverall, outOfSpec, defectRate, violations }

Confidence intervals

Every figure the grid reports is an estimate from the rows in front of it. interval() says how tightly that estimate is pinned down: the range a mean is likely to sit in, with its margin of error, rather than a single number read to more decimal places than the data earns. Ask for a proportion instead with kind: 'proportion', and process capability can report an interval on Cpk too, which is what turns "the process is capable" into "capable, on this many parts".

grid.statistics.interval('margin');
// { mean, lower, upper, margin, n, confidence }  a 95% interval by default

grid.statistics.interval('passed', { kind: 'proportion' });
// { proportion, lower, upper, n, confidence }

grid.statistics.interval('margin', { confidence: 0.99 }); // a wider, surer interval

It reads the rows the filters leave, so the interval narrows as the grid narrows: it describes the population on screen, not the whole table. It is a range, not a verdict; the grid states how well the figure is known and leaves the judgement to you.

Bayesian estimate for a rate

statistics.bayes(colId, opts) answers "how likely is it that this group's rate is really higher than that one's?" for a yes/no column. Pass by to split the rows by a second column; the Compare groups panel shows the same estimate beside its test result.

const grid = createGrid(el, {
  rowKey: 'id',
  columns: [
    { field: 'converted', type: 'text' },
    { field: 'variant', type: 'text' },
  ],
  rows: [
    { id: 1, variant: 'a', converted: 'yes' }, { id: 2, variant: 'a', converted: 'no' },
    { id: 3, variant: 'a', converted: 'no' },  { id: 4, variant: 'b', converted: 'yes' },
    { id: 5, variant: 'b', converted: 'yes' }, { id: 6, variant: 'b', converted: 'no' },
  ],
});

const r = grid.statistics.bayes('converted', { by: 'variant' });
// r.groups[0]  { label: 'a', successes: 1, trials: 3, mean, lower, upper, ... }
// r.probabilityHigher  the probability that b's rate is higher than a's

grid.statistics.bayes('converted', { by: 'variant', prior: 'jeffreys' });
grid.statistics.bayes('converted', { by: 'variant', category: 'no' }); // count "no" instead

The result holds prior, level, category and one entry per group in groups, each with successes, trials, the posterior mean and its credible interval as lower and upper. With exactly two groups it also holds probabilityHigher, the probability that the second group's rate is higher than the first's. It returns null for a column that is not yes/no.

The default prior is 'uniform', which assumes nothing about the rate before the rows are read. Choose 'jeffreys', or { alpha, beta } with your own positive shapes, through prior; level sets the interval, 0.95 by default. A yes/no column counts its "yes" value unless category names another, and a category the column does not hold returns null.

Distribution-driven formatting

The same knowledge drives conditional formatting that describes the data rather than a threshold you typed: an { op: 'outlier' } rule flags the statistical extremes, and a colour scale with from: 'quantile' spans a percentile range so a single large value does not flatten it. See the data-driven rules and quantile scales demos.

See the statistics overview and its live demos.