Charts API & eventsCharts
Every option, method and event of Birch UI Charts, with the exported helpers and types.
Everything here is exported from @birchui/charts. The tables below are generated from the package's TypeScript source; the package reference lists every exported type.
createChart#
import { createChart, type ChartApi, type ChartOptions } from '@birchui/charts';
const chart: ChartApi<Order> = createChart<Order>(container, options);createChart<TDatum>(container, options) creates a chart inside container and returns its ChartApi. The generic parameter types xKey, yKey, sizeKey and colorKey, the datum in events and tooltips, and setData(). It throws a TypeError when container is not an element or options is not an object.
Options#
| Option | Default | Notes |
|---|---|---|
series |
required | See Series |
data |
none | Shared rows; a series can override it with its own data |
title, subtitle |
none | Drawn above the plot and used in the accessible summary |
axes |
inferred | See Axes |
legend |
automatic | Shown for two or more series, and always for pie and donut charts |
tooltip |
on, shared | See Interaction |
zoom |
on | See Interaction |
animation |
on, 450 ms | false, or { enabled, duration }; skipped for reduced motion |
padding |
16 |
Pixels around the chart, as a number or { top, right, bottom, left } |
theme |
'auto' |
'light', 'dark' or 'auto' |
palette |
DEFAULT_PALETTE |
Series colors, used in order |
height |
320 |
Pixels or any CSS length; 32 for sparklines |
sparkline |
false |
Hides axes, legend and title, and turns off zoom |
locale |
browser locale | Used for numbers, dates and the summary |
accessibility |
see Accessibility | label, dataTable, keyboardNavigation |
renderer |
'auto' |
'canvas', 'svg' or a custom backend factory, see Rendering backends |
pixelRatio |
devicePixelRatio |
Canvas resolution |
injectStyles |
true |
false to load @birchui/charts/styles.css yourself |
licenseKey |
the key from setLicenseKey() |
See Licensing |
ChartApi#
| Method | Description |
|---|---|
update(partial) |
Apply only the options passed. Changes to data and series animate. |
getOptions() |
A copy of the current options |
setData(data) |
Shorthand for update({ data }) |
setSeries(series) |
Shorthand for update({ series }) |
setSeriesVisible(id, visible) |
Show or hide a series by ID, or a pie or donut slice by its label |
isSeriesVisible(id) |
Whether a series or slice is visible |
setZoom(range) |
Zoom the x axis to [min, max], or reset with null |
getZoom() |
The current zoom range, or null |
resetZoom() |
Show the full range |
setDataTableVisible(visible) |
Show or visually hide the data table |
toSVG(options?) |
The chart as an SVG string |
toPNG(options?) |
A Promise<Blob> with a PNG image |
download(format, fileName?) |
Save as 'png' or 'svg' |
on(event, listener) |
Subscribe; returns an unsubscribe function |
destroy() |
Remove the chart and release every listener, observer and animation frame |
element |
The root element |
Events#
ready#
{ chart }. Fires once, in a microtask after createChart() returns, so a listener attached right after creation receives it.
pointClick#
{ point, event }. Fires when the user clicks a point, bar, slice or cell, or presses Enter or Space on a point focused with the keyboard. point is a ChartPoint with the series ID, name and index, the point index, the original datum and the raw x and y.
chart.on('pointClick', ({ point }) => {
const order = point.datum;
drawer.open(`/orders/${order.id}`);
});legendToggle#
{ seriesId, name, visible, sliceIndex? }. Fires when a legend entry is toggled. For pie and donut slices, sliceIndex is the slice position and seriesId the pie series.
zoomChange#
{ range, source }. Fires on every zoom or pan. range is [min, max] in x axis units or null for the full range; source is 'drag', 'wheel', 'pinch', 'pan', 'keyboard', 'api' or 'reset'.
seriesHover#
{ seriesId, point }. Fires when the hovered or keyboard-focused point changes, with null values when nothing is hovered.
Exported helpers#
| Export | Description |
|---|---|
chartDefinition |
The widget definition (name: 'BirchChart', tagName: 'birchui-chart', the five events) for framework factories and custom elements |
chartFromRange(values, headers, options?) |
Chart options from a 2-D range of cells. See Grid integration |
parseCellNumber(value) |
Parses numbers and formatted numeric text such as $1,265,000, 12.5% and (2,500); NaN otherwise |
sparklineSVG(values, options?) |
A sparkline as an SVG string |
escapeHtml(text) |
Escapes &, <, >, " and ' for use in tooltip HTML |
checkPaletteContrast(palette, backgrounds, minimum?) |
Contrast report per color and background |
contrastRatio(a, b) |
WCAG contrast ratio of two colors |
DEFAULT_PALETTE |
The eight default series colors |
chartStyles |
The chart CSS as a string |
createRecordingRenderer() |
A render backend that records display lists, for tests |
walkPath(path, visitor) |
Iterates the commands of a recorded path |
Rendering backends#
Charts draw through a small RenderBackend interface that receives a display list of rectangles, paths, markers and text. Two backends are built in:
- Canvas, used by default (
renderer: 'auto'or'canvas'). - SVG (
renderer: 'svg'), drawn as DOM elements.'auto'falls back to SVG where Canvas 2D is not available, and'canvas'falls back with a console warning.
Pass a factory to plug in your own backend. For tests, createRecordingRenderer() returns a backend that records each frame's display list instead of drawing, so you can assert on what a chart configuration would draw without a canvas:
import { createChart, createRecordingRenderer } from '@birchui/charts';
const host = document.body.appendChild(document.createElement('div'));
const recorder = createRecordingRenderer();
const chart = createChart(host, {
data: revenue,
series: [{ type: 'column', xKey: 'month', yKey: 'europe', name: 'Europe' }],
renderer: recorder.factory,
animation: false,
});
await new Promise(requestAnimationFrame);
const frame = recorder.lastFrame('main');
console.info(frame?.items.length, 'display items drawn');
chart.destroy();recorder.frames holds every recorded frame with its layer, size, pixel ratio and display items (rectangles, paths, markers, text and groups of them); lastFrame(layer?) returns the latest one, and destroyed() counts destroyed backends, which helps assert that destroy() cleans up.
Types#
The package exports types for every option and payload, including ChartOptions, SeriesOptions, AxisOptions, AxesOptions, LegendOptions, TooltipOptions, TooltipContext, TooltipPoint, ZoomOptions, AnimationOptions, AccessibilityOptions, ExportOptions, ChartPoint, ChartEvents, ChartApi, SeriesType, AxisType, CurveType, StackMode and ZoomSource. See the @birchui/charts reference.