DEV Community

Cover image for JavaScript Box Plot: Charting Ten Million Latency Samples by the Hour
Chart Tech
Chart Tech

Posted on

JavaScript Box Plot: Charting Ten Million Latency Samples by the Hour

TL;DR

A box plot shrinks a large group of numbers into five values: the minimum, the first quartile, the median, the third quartile and the maximum. With millions of raw samples, the slow part is computing those numbers and drawing the outliers, because drawing the boxes themselves is cheap. In our test, 10 million latency samples became 720 hourly boxes and 350,690 outlier dots. This guide shows how to compute the quartiles off the main thread, keep live boxes current with a fixed-size histogram, and draw every box and outlier on the GPU.

Box plots are one of the oldest tools in statistics, and they still earn a place on engineering dashboards. One glance at a box tells you where the typical value sits, how spread out the values are, and how many points fall far away from the rest. An average can't show any of that, so teams reach for box plots whenever the spread of a value is the real story.

The trouble starts when a box plot is fed raw data at production scale. A month of request latencies can run to tens of millions of samples, and most charting tutorials assume a few hundred. By the end of this guide, you will know how to turn millions of samples into box plot rows without freezing the page, when a streaming histogram is the better choice, and how to draw hundreds of thousands of outliers on the GPU.

What a Box Plot Shows About One Hour of Request Latency

Suppose we have a platform team running a public API. Every request writes its latency in milliseconds to a log, which comes to about 10 million samples over 30 days. The team wants one box per hour, so they can see how latency behaves during busy and quiet periods.

Each box summarizes one hour with five numbers, often called the five-number summary:

  • Median: the middle value once the hour's samples are sorted. Half the requests were faster and half were slower.
  • First quartile (Q1) and third quartile (Q3): the values a quarter and three quarters of the way through the sorted samples. The box is drawn from Q1 to Q3.
  • Interquartile range (IQR): the distance from Q1 to Q3. It holds the middle half of the requests.
  • Whiskers: the lines that reach out from the box to the lowest and highest samples that still count as normal.
  • Outliers: samples past the whiskers, drawn as separate dots.

Most tools decide what counts as normal with the Tukey rule. Any sample more than 1.5 times the IQR below Q1 or above Q3 is an outlier, and the whiskers stop at the most extreme samples inside those limits. For latency data, the outliers are the requests users complain about, so they deserve as much care as the boxes.

Why Ten Million Raw Samples Stall Most Box Plot Libraries

Many charting libraries accept raw samples and compute the five numbers for you. ApexCharts' box plot from raw observations demo works this way, with the library deriving the summary from each raw array. That's convenient for a few thousand points, but every quartile needs a sort, and sorting millions of numbers on the main thread blocks clicks, scrolling and every other chart on the page.

The outliers are the second and larger cost. We generated 10 million synthetic latencies with a log-normal shape and a small share of very slow requests, then grouped them by hour. The 720 boxes were trivial to draw, but the Tukey rule flagged 350,690 samples, about 3.5%, as outliers. A chart that draws each outlier as an SVG element puts hundreds of thousands of nodes into the page, and the browser has to lay out and repaint every one of them.

So the work splits into three parts:

  • Compute the five numbers away from the main thread.
  • Send the chart only the summary rows and the outlier coordinates.
  • Draw the outliers with a renderer that can handle hundreds of thousands of points.

Before and after: raw samples summarized on the main thread with SVG outliers, compared with a Web Worker summary and GPU-drawn boxes

Computing the Five Numbers Once Per Hour in a Web Worker

The exact approach groups samples by hour, sorts each group and reads the quartiles from the sorted array. Typed arrays such as Float64Array sort numerically by default and use far less memory than plain arrays, so the grouping step copies each hour into its own typed array:

// boxStats.ts: library-agnostic, no chart code here
export interface BoxRow {
  x: number; min: number; q1: number; median: number; q3: number; max: number;
}

function quantile(sorted: Float64Array, p: number): number {
  const pos = (sorted.length - 1) * p;
  const lo = Math.floor(pos);
  const hi = Math.ceil(pos);
  return sorted[lo] + (sorted[hi] - sorted[lo]) * (pos - lo);
}

export function buildBoxes(timestamps: Float64Array, values: Float64Array, bucketSeconds: number) {
  // 1. Count samples per bucket so each group gets one typed array.
  const counts = new Map<number, number>();
  for (let i = 0; i < timestamps.length; i++) {
    const b = Math.floor(timestamps[i] / bucketSeconds) * bucketSeconds;
    counts.set(b, (counts.get(b) ?? 0) + 1);
  }
  const groups = new Map<number, { data: Float64Array; n: number }>();
  for (const [b, c] of counts) groups.set(b, { data: new Float64Array(c), n: 0 });

  // 2. Copy each value into its group.
  for (let i = 0; i < timestamps.length; i++) {
    const b = Math.floor(timestamps[i] / bucketSeconds) * bucketSeconds;
    const g = groups.get(b)!;
    g.data[g.n++] = values[i];
  }

  // 3. Sort each group, then read quartiles, Tukey whiskers and outliers.
  const rows: BoxRow[] = [];
  const outX: number[] = [];
  const outY: number[] = [];
  for (const b of [...groups.keys()].sort((a, c) => a - c)) {
    const sorted = groups.get(b)!.data.sort();
    const q1 = quantile(sorted, 0.25);
    const median = quantile(sorted, 0.5);
    const q3 = quantile(sorted, 0.75);
    const fenceLo = q1 - 1.5 * (q3 - q1);
    const fenceHi = q3 + 1.5 * (q3 - q1);
    let min = median;
    let max = median;
    for (const v of sorted) {
      if (v < fenceLo || v > fenceHi) { outX.push(b); outY.push(v); }
      else { if (v < min) min = v; if (v > max) max = v; }
    }
    rows.push({ x: b, min, q1, median, q3, max });
  }
  return { rows, outlierX: Float64Array.from(outX), outlierY: Float64Array.from(outY) };
}
Enter fullscreen mode Exit fullscreen mode

A Web Worker runs this on a background thread. The page hands over the raw buffers as transferable objects, which moves them to the worker without copying, and the worker sends back one column per field:

// boxWorker.ts
import { buildBoxes } from "./boxStats";

self.onmessage = (e: MessageEvent<{ ts: Float64Array; ms: Float64Array }>) => {
  const { rows, outlierX, outlierY } = buildBoxes(e.data.ts, e.data.ms, 3600);
  const col = (k: "x" | "min" | "q1" | "median" | "q3" | "max") =>
    Float64Array.from(rows, (r) => r[k]);
  const msg = {
    x: col("x"), min: col("min"), q1: col("q1"), median: col("median"),
    q3: col("q3"), max: col("max"), outlierX, outlierY,
  };
  (self as unknown as Worker).postMessage(msg, [
    msg.x.buffer, msg.min.buffer, msg.q1.buffer, msg.median.buffer,
    msg.q3.buffer, msg.max.buffer, outlierX.buffer, outlierY.buffer,
  ]);
};
Enter fullscreen mode Exit fullscreen mode

On our test machine, the whole pass over 10 million samples took about 1.2 seconds in Node and about 1.9 seconds in headless Chrome, counting the transfer in and out of the worker. The page stayed responsive the whole time, because none of that work ran on the main thread. Your numbers will differ with hardware, so time it on the slowest machine your users have.

Keeping Live Boxes Current With a Log-Bucket Histogram

The exact approach needs every sample of an hour in memory before it can sort. That's fine for a historical report, but a live dashboard wants the current hour's box to move as requests arrive, without storing millions of values and re-sorting them every second.

A log-bucket histogram solves this. It splits the value range into buckets whose width grows with the value, so a bucket near 10 ms is narrow and a bucket near 10 seconds is wide. Each new sample becomes one counter increment, and a quartile is read by walking the counts until a quarter, half or three quarters of the total is reached:

export class LogHistogram {
  private readonly counts: Uint32Array;
  private readonly logBase: number;
  total = 0;

  constructor(private readonly minValue: number, maxValue: number, relativeError = 0.01) {
    this.logBase = Math.log((1 + relativeError) / (1 - relativeError));
    const size = Math.ceil(Math.log(maxValue / minValue) / this.logBase) + 1;
    this.counts = new Uint32Array(size);
  }

  add(value: number): void {
    const v = Math.max(value, this.minValue);
    const i = Math.min(this.counts.length - 1,
      Math.floor(Math.log(v / this.minValue) / this.logBase));
    this.counts[i]++;
    this.total++;
  }

  quantile(p: number): number {
    const target = p * (this.total - 1);
    let seen = 0;
    for (let i = 0; i < this.counts.length; i++) {
      seen += this.counts[i];
      if (seen > target) return this.minValue * Math.exp((i + 0.5) * this.logBase);
    }
    return this.minValue * Math.exp(this.counts.length * this.logBase);
  }
}
Enter fullscreen mode Exit fullscreen mode

We checked this against the exact quartiles for all 720 hours of the test data. With a range of 0.1 ms to 60 seconds and a 1% setting, each hour used 667 buckets, which is about 2.7 KB of memory no matter how many requests arrive. The largest gap from the exact Q1, median or Q3 across every box was 1.0%.

![How a log-bucket histogram finds a quartile: bucket counts add up from left to right until they pass 25 percent of the total][
(https://dev-to-uploads.s3.us-east-2.amazonaws.com/uploads/articles/acnzehq10at9hnqbyz5l.png)

The histogram can't list individual outliers, because it stores only a count per bucket. A common pattern is to keep a small buffer of samples past the current upper fence for each live hour, then replace the live box with an exact one once the hour closes.

Drawing the Hourly Boxes With SciChart on the GPU

With the summary rows ready, any library that accepts precomputed statistics can draw the boxes. Plotly's box trace takes q1, median and q3 arrays, for example. The outliers still need a renderer that can draw 350,690 points smoothly while the user pans and zooms.

SciChart.js is a charting library that renders through WebAssembly and the GPU. Version 6 supports WebGPU and WebGL 2. By default, it tries WebGPU on Apple Silicon Macs and uses WebGL 2 elsewhere. It ships a box plot series, FastBoxPlotRenderableSeries, which reads the five numbers from a BoxPlotDataSeries, and a scatter series that draws large point sets on the GPU. Install SciChart.js v6:

npm install scichart@6
Enter fullscreen mode Exit fullscreen mode

The chart takes the worker's columns as they are, with no conversion to objects:

import {
  SciChartSurface, SciChartJSLightTheme, DateTimeNumericAxis, LogarithmicAxis,
  BoxPlotDataSeries, FastBoxPlotRenderableSeries, XyDataSeries, XyScatterRenderableSeries,
  EllipsePointMarker, EDataPointWidthMode, ENumericFormat, NumberRange,
  ZoomPanModifier, MouseWheelZoomModifier, ZoomExtentsModifier,
} from "scichart";

export interface BoxColumns {
  x: Float64Array; min: Float64Array; q1: Float64Array; median: Float64Array;
  q3: Float64Array; max: Float64Array; outlierX: Float64Array; outlierY: Float64Array;
}

export async function drawLatencyBoxes(divId: string, d: BoxColumns) {
  const { sciChartSurface, wasmContext } = await SciChartSurface.create(divId, {
    theme: new SciChartJSLightTheme(),
  });

  sciChartSurface.xAxes.add(new DateTimeNumericAxis(wasmContext, {
    growBy: new NumberRange(0.01, 0.01),
  }));
  sciChartSurface.yAxes.add(new LogarithmicAxis(wasmContext, {
    logBase: 10, labelFormat: ENumericFormat.Decimal, labelPrecision: 0,
    axisTitle: "Latency (ms)",
  }));

  // Outliers go in first so the boxes draw on top of them.
  sciChartSurface.renderableSeries.add(new XyScatterRenderableSeries(wasmContext, {
    dataSeries: new XyDataSeries(wasmContext, {
      xValues: d.outlierX, yValues: d.outlierY, isSorted: true, containsNaN: false,
    }),
    pointMarker: new EllipsePointMarker(wasmContext, {
      width: 2, height: 2, fill: "#9AA3B2", strokeThickness: 0,
    }),
    opacity: 0.4,
  }));

  // One box per hour: six arrays of equal length.
  const boxes = new BoxPlotDataSeries(wasmContext, {
    xValues: d.x,
    minimumValues: d.min,
    lowerQuartileValues: d.q1,
    medianValues: d.median,
    upperQuartileValues: d.q3,
    maximumValues: d.max,
    isSorted: true,
    containsNaN: false,
  });

  sciChartSurface.renderableSeries.add(new FastBoxPlotRenderableSeries(wasmContext, {
    dataSeries: boxes,
    fill: "#2547FF", stroke: "#1A33B8", strokeThickness: 1, opacity: 0.8,
    dataPointWidthMode: EDataPointWidthMode.Relative,
    dataPointWidth: 0.7,
    whiskers: { stroke: "#5B6475", strokeThickness: 1 },
    cap: { stroke: "#5B6475", strokeThickness: 1, dataPointWidth: 0.4 },
    medianLine: { stroke: "#FFFFFF", strokeThickness: 1 },
  }));

  sciChartSurface.chartModifiers.add(
    new ZoomPanModifier(), new MouseWheelZoomModifier(), new ZoomExtentsModifier(),
  );
  return { sciChartSurface, wasmContext, boxes };
}
Enter fullscreen mode Exit fullscreen mode

A few choices in this sample are worth explaining:

  • Log axis: latency is skewed, with most requests near 40 ms and a long tail into seconds. A LogarithmicAxis keeps both the boxes and the slowest outliers readable on one chart.
  • Zoom stays usable: the axes keep their default auto-range, so ZoomPanModifier and MouseWheelZoomModifier aren't overridden on every redraw.
  • Data flags: isSorted and containsNaN tell SciChart the data is in time order and has no gaps, which lets it skip extra checks. Without them, SciChart logs a performance warning in the console.
  • Box width: EDataPointWidthMode.Relative sizes each box as a share of the spacing between hours, which suits evenly spaced buckets.

We ran this exact code in headless Chrome with scichart 6.0.17. Reading the data series back confirmed 720 boxes and 350,690 outlier points. The capture below shows three days of the 30, zoomed with the same axis the user would drag, and it carries the community edition watermark.

SciChart.js box plot of hourly request latency over three days, with outliers drawn as grey dots on a logarithmic axis

Two details in the SciChart API are easy to trip over:

  • update() takes its values in a different order from append(): append(x, max, q3, median, q1, min) puts the maximum first, while update(index, median, max, q3, q1, min) puts the median first. We confirmed this by updating a box in the browser and reading each value back. When the live histogram refreshes the current hour, pass the median first.
  • No per-box colors on the box series: the type definitions note that paletteProvider isn't supported by FastBoxPlotRenderableSeries. To highlight hours that breach a latency target, put them in a second box series with its own fill.

The community edition is free for non-commercial use and for a limited commercial evaluation, with a watermark on every chart, and each community build stops working six months after its release date. Commercial licences are per developer, with prices on the SciChart store.

Where Should You Start

The boxes in a large box plot are cheap. The cost sits in computing quartiles over millions of samples and in drawing the outliers those quartiles produce. Moving the sort into a Web Worker keeps the page responsive, a log-bucket histogram keeps live boxes current in a few kilobytes, and a GPU-rendered scatter series draws hundreds of thousands of outliers without slowing the page down.

Start by running the exact buildBoxes function on one day of your own data and counting the outliers it returns. If the count runs into the tens of thousands, draw them with a GPU renderer such as SciChart.js; its box plot documentation and live box plot demo show the full set of styling options. Once the historical view works, add the histogram for the current hour.

Frequently Asked Questions About JavaScript Box Plots

How many data points can a JavaScript box plot handle?

The box count is rarely the limit, since 720 hourly boxes is a small amount of geometry for any renderer. The limits are the sort over raw samples and the number of outliers. Compute the statistics in a Web Worker and draw outliers with a GPU renderer, and millions of raw samples work fine.

Should a browser compute box plot quartiles or should the server?

If the samples already live in a database, computing quartiles there and sending only the summary rows saves bandwidth. Browser-side computation suits data that arrives in the page anyway, such as a live stream or a file the user uploads. The buildBoxes function works in both places, since it has no browser dependencies.

What is the 1.5 IQR rule for box plot outliers?

The interquartile range (IQR) is Q3 minus Q1. Any value more than 1.5 times the IQR below Q1 or above Q3 is treated as an outlier, and the whiskers stop at the most extreme values inside those limits. This is the convention most charting and statistics tools use.

How accurate is a histogram-based median compared with sorting?

That depends on the bucket width you choose. With 1% relative-width buckets, every quartile in our 720-hour test stayed within 1.0% of the sorted result. Narrower buckets improve accuracy at the cost of more memory per box.

Does SciChart.js compute quartiles from raw data?

No, BoxPlotDataSeries takes precomputed values: x positions plus minimum, lower quartile, median, upper quartile and maximum arrays. That's why the statistics step in this guide is separate and works with any chart library.

How do I show box plot outliers in SciChart.js?

Add an XyScatterRenderableSeries alongside the box series, using the outlier x positions and values from your statistics step. Add the scatter series first so the boxes draw on top of the dots.

Top comments (0)