# Large data

> Draw line and area charts with a million points through per-pixel min/max decimation, and know when to decimate, aggregate or switch chart types.

Birch UI Charts draws line and area series with hundreds of thousands or millions of points without sampling away the peaks. The work per frame depends on the width of the chart, not on the number of points.

**Live demo: One million telemetry points** (runs on the HTML version of this page). Source of `demos/chart-large-line.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import { createChart } from '@birchui/charts';
import { button, docsTheme, layout, onDocsThemeChange, seededRandom } from './_shared';

export const meta = { title: 'One million telemetry points', height: 460 };

interface Reading {
  time: number;
  temperature: number;
}

const POINT_COUNT = 1_000_000;
const START = Date.UTC(2026, 9, 1);
const INTERVAL_MS = 2_000;

function makeReadings(): Reading[] {
  const random = seededRandom(17);
  const readings: Reading[] = new Array(POINT_COUNT);
  let value = 21;
  for (let i = 0; i < POINT_COUNT; i++) {
    const daily = Math.sin((i / 43_200) * Math.PI * 2) * 2.5;
    value += (random() - 0.5) * 0.08 - (value - 21) * 0.0005;
    const spike = random() < 0.00002 ? 6 + random() * 4 : 0;
    readings[i] = { time: START + i * INTERVAL_MS, temperature: Math.round((value + daily + spike) * 100) / 100 };
  }
  return readings;
}

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  const generated = performance.now();
  const data = makeReadings();
  const started = performance.now();
  const chart = createChart<Reading>(body, {
    title: 'Cold storage unit 4: temperature',
    subtitle: `${POINT_COUNT.toLocaleString()} readings, one every 2 seconds`,
    data,
    series: [{ type: 'line', xKey: 'time', yKey: 'temperature', name: 'Temperature (°C)', decimation: true }],
    axes: { x: { type: 'time' }, y: { title: '°C' } },
    zoom: true,
    legend: false,
    theme: docsTheme(),
    height: '100%',
  });
  const rendered = Math.round(performance.now() - started);
  status.textContent = `Generated in ${Math.round(started - generated)} ms, first render in ${rendered} ms. Drag across the plot to zoom.`;
  toolbar.append(
    button('Zoom to first day', () => chart.setZoom([START, START + 86_400_000])),
    button('Reset zoom', () => chart.resetZoom()),
    button('Download PNG', () => {
      chart.download('png', 'cold-storage-unit-4').catch((error: Error) => {
        status.textContent = `Export failed: ${error.message}`;
      });
    }),
  );
  const offZoom = chart.on('zoomChange', ({ range, source }) => {
    status.textContent = range
      ? `Showing ${new Date(range[0]).toISOString().slice(0, 16)} to ${new Date(range[1]).toISOString().slice(0, 16)} UTC (${source})`
      : 'Showing the full range.';
  });
  const stopTheme = onDocsThemeChange((theme) => chart.update({ theme }));
  return () => {
    offZoom();
    stopTheme();
    chart.destroy();
  };
}
```

## How decimation works

When a line or area series has more points in the visible range than twice the plot width in pixels, the chart divides the range into one bucket per pixel column and keeps, for each column:

- the first point,
- the last point,
- the point with the minimum value,
- the point with the maximum value.

That is at most four points per pixel, whatever the size of the dataset. Because every spike and dip in a column survives, the decimated line looks the same as the full line at that width; nothing is lost visually. Gaps (missing values) are preserved too.

Decimation is recomputed for the visible range, so zooming in reveals the individual points: zoom far enough and the series is drawn point by point, with markers once points are at least 18 pixels apart.

## A million points

```ts title="telemetry-1m.ts"
import { createChart } from '@birchui/charts';

const POINTS = 1_000_000;
const start = Date.UTC(2026, 9, 1);
const intervalMs = 2_000;

const readings = new Array(POINTS);
let vibration = 0.42;
for (let i = 0; i < POINTS; i++) {
  vibration += (Math.random() - 0.5) * 0.02;
  if (i % 86_400 === 43_200) vibration += 0.35;
  readings[i] = { recordedAt: start + i * intervalMs, mmPerSecond: Math.max(0, vibration) };
}

const chart = createChart(document.querySelector<HTMLElement>('#pump-vibration')!, {
  title: 'Pump P-14 vibration',
  subtitle: '1,000,000 readings at 2-second intervals',
  data: readings,
  series: [{ type: 'line', xKey: 'recordedAt', yKey: 'mmPerSecond', name: 'Vibration (mm/s)' }],
  axes: { x: { type: 'time', utc: true }, y: { title: 'mm/s' } },
  animation: false,
});

chart.on('ready', () => console.info('first render done'));
```

Timestamps are numbers here, so `type: 'time'` tells the chart to format them as dates; with `Date` objects or ISO strings it would infer a time axis by itself.

### Measured performance

The package README reports that a 1,000,000-point line prepares and renders in about 40 to 250 ms depending on the machine, and the package's test suite checks that decimating and building the path for 1,000,000 points stays under 300 ms. Your numbers depend on the device, the browser and what else the page is doing, so measure on the hardware your users have.

Tooltips stay instant at this size: the nearest point is found by binary search over the sorted x values.

## Getting the most out of it

- **Pass sorted x values.** Decimation and the tooltip search work on data sorted by x. The chart sorts unsorted series for you while preparing data, but sorting a million points costs time on every data change; sort once on the server or when you load the data.
- **Use numbers or `Date` objects for x.** ISO strings work, but every string has to be parsed. Epoch milliseconds with `axes.x.type: 'time'` are the cheapest.
- **Turn animation off for very large series.** `animation: false` skips the transition between old and new values when you call `setData()`, which matters most when data changes often.
- **Keep decimation on.** `decimation: false` on a series draws every point. Use it only for short series where you need exact pixel output, for example in tests.
- **Reuse the chart.** Call `setData()` or `update()` instead of destroying and recreating the chart; the canvas, observers and layout are kept.

## When to use it

Decimation is the right tool when the shape of a long series is the message: sensor telemetry, server metrics, price histories, traffic per minute over a year. It keeps every extreme value, so alarms and outages remain visible.

It is not a substitute for aggregation:

| Situation | Better approach |
| --- | --- |
| Users read exact values per period ("orders per day") | Aggregate to days, weeks or months on the server and draw a column or line chart of the totals |
| Many series overlap into a solid band | Show fewer series, use small multiples, or a heatmap of value by time and series |
| Hundreds of thousands of points without an order, such as measurements of two variables | A scatter chart; above 20,000 points it draws at most one marker per pixel |
| A trend in a table cell | A [sparkline](https://docs.birchui.com/charts/grid-integration.md#sparklines-in-grid-cells) of a few dozen aggregated values |

Bar and column series are not decimated: a bar per category is meant to be read, so aggregate first when you have thousands of categories.

## Exporting large charts

`toSVG()` and `toPNG()` export what is drawn, so a decimated line exports as at most four points per pixel column of the export width. A wide export (`toPNG({ width: 4000 })`) keeps more detail. See [Export](https://docs.birchui.com/charts/export.md).
