aerizchart

@aeriz/chartDOCS

26 canvas chart types, each drawn from one options object. One way to use them, with the same names and options in React, Vue, Svelte and jQuery.

v2.1.1 · one chart 12–17 KB · all 35 KB (gzip) · zero deps

Introduction

@aeriz/chart draws 26 canvas chart types from one options object. Pass a container and your data; axes, legend, tooltips, animation and theme come from sensible defaults.

  • One way to do it Data is data, changes go through update(), states through setState(). Same in all 26 charts and five environments.
  • Tells you what's wrong A misspelled option or unreadable data prints the fix in the console instead of drawing nothing.
  • Only what you use One module per chart, so bundles keep only the charts you import. Zero runtime dependencies.
  • Works anywhere Vanilla JS, React, Vue, Svelte and jQuery share the same names and options.
  • Easy events Clicks, hover, the legend and tooltip buttons are each one function. Detail pages, popups and drill-downs take a few lines. Events
  • Fast A million points in about 50 ms. Off-screen charts don't draw.

New in 2.1.1 Links and buttons and your own content in tooltips, legend clicks you can take over, and the item under the pointer. Code for 2.1 runs as it is.

New in 2.1 Reference lines and bands, zoom and brush, sync, 100% stacking, error bars, more value axes, plus candlestick, treemap and sunburst, sankey, network and map. Code for 2.0 runs as it is.

Examples

Examples built like real product screens. They all run on this page, and the JS, HTML and CSS tabs hold all of the code behind each one. Every chart is new SomeChart(element, { data }) plus a few options. For each chart type on its own, see Chart types.

Sales dashboard

@aeriz/chart · 38 lines of JS

Eight charts: KPI cards, a combo chart, a donut, a heatmap and a funnel. Each chart takes a few options, and the monthly/quarterly switch is a single update().

Online storeJan–Dec 2026
Revenue$13.92M▲ 18.4%
Orders312K▲ 11.0%
Average order$44.60▲ 6.7%
Conversion3.0%▲ 0.4 pt

Revenue and margin

Sales channels

Orders by day and hour

Checkout funnel

Business review · complex charts

@aeriz/chart · 97 lines of JS

Nine charts: a four-layer combo with a right axis, a stacked area, an ARR bridge, cohort retention, quartile distributions, 20,000 points and an 8,760-cell heatmap. One segment button calls update() on all of them.

Subscription business review 2026
Loading…

Weekly sign-ups · bars + area + line + dots, right axis

Sign-ups (bars) and their 8-week average (area) use the left axis, conversion (line) the right % axis. Red dots mark weeks far off the average.

Acquisition by channel · stacked area

Click the legend to drop a channel. The rest restack.

Annual recurring revenue (ARR) bridge

From opening ARR through new, expansion, contraction and churn to closing.

Cohort retention by sign-up month

Months that have not happened yet stay empty (null).

Session length by plan

Quartiles and outliers computed from 8,000 sessions.

Competitor comparison

Six survey items, out of 10.

20,000 users · active days vs monthly spend

Colored by plan. Hover picks out a single user.

Users by plan

Counted from the same data as the cloud.

365 days × 24 hours of traffic · 8,760 cells

Weekends and commute hours stand out. Every cell has a tooltip.

Drill-down · one million points

@aeriz/chart · 43 lines of JS

Click a region bar and onClick switches the other charts to that region, then rebuilds and redraws 1,000,000 per-second transactions. The time it took is printed at the top.

Regions and stores Loading… Click a bar on the left, or focus the chart and use ↑ ↓ Enter.

Revenue by region

Seoul · monthly revenue vs last year

Seoul · 24 stores (floor area · revenue · staff)

Seoul · payment server, 1,000,000 per-second samples (11 days 14 hours)

Server monitoring

@aeriz/chart · 23 lines of JS

A live line that moves every 0.1 s, three gauges and response time per API. Press "Simulate an outage".

api-prod · Seoul region Healthy

Response time (every 0.1 s)

p95 by API

Survey report

@aeriz/chart · 18 lines of JS

Put the same charts on white paper and they read the text and background colors to switch to a light theme. Brand colors are two CSS variables.

2026 customer satisfaction survey · 1,284 responses

Service satisfaction report

Overall satisfaction is 4.3 out of 5, up 0.4 from last year. Scores rose in every age group, and faster delivery made the biggest difference.

Satisfaction by topic
By age, compared with last year
Would recommend

Install

Pick your package manager. Without a build step, use the CDN tab.

bash
npm install @aeriz/chart

The npm package holds only the minified build (dist/) and the TypeScript types.

  • import → dist/esm/, one file per chart
  • require → dist/aeriz.min.cjs
  • CDN script → dist/aeriz.min.js

Minifying only shortens local names. Option names, methods, chart names and error messages read as they are.

Tip Pin an exact version in CDN URLs, like @2.1.1. Those URLs never change, so they are cached for a year.

Quick start

All you need is an element with a height and some data. Without a height the chart uses 320px.

html
<div id="sales" style="height: 260px"></div>
<script type="module">
  import { BarChart } from '@aeriz/chart';

  const chart = new BarChart('#sales', {
    data: { Jan: 64, Feb: 42, Mar: 78, Apr: 55, May: 90, Jun: 71 },
  });

  chart.update({ data: { Jan: 30, Feb: 80 } }); // animates to the new values
</script>

Hover a bar, or focus the chart and read the values with ← →.

One way to use it

Every chart uses the same four calls. There are no other names for the same thing.

ToUse
Createnew BarChart(element or selector, options)
Change data or optionschart.update({ data, … }) — pass only what changed; values animate
Loading · empty · errorchart.setState('loading' | 'empty' | 'error', text?), and chart.setState(null) to close
Redraw right nowchart.render() — re-reads CSS variables and draws the final frame immediately, even off-screen
Removechart.destroy() — puts the element back as it was

Only RealtimeChart adds push() to stream values and clear() to empty it.

Data shapes

Data always goes in the one data option. Its shape follows what the chart draws.

One value per item

Bar, HBar, Line, Sparkline, Pie, Polar, Funnel, Treemap, Sunburst and Map take any of these three. They all mean the same.

js
new BarChart(el, { data: [64, 42, 78] });                  // numbers → labels 1, 2, 3
new BarChart(el, { data: { Jan: 64, Feb: 42 } });          // object → keys are labels
new BarChart(el, { data: [{ label: 'Jan', value: 64 }] }); // rows

// Rows with other field names: say how to read them
new BarChart(el, { data: rows, label: (r) => r.month, value: (r) => r.sales });

Several series

Area, StackedBar, GroupedBar, MultiLine, Radar and Composite take categories and series inside data. Each series has one value per category. For error bars and bands, add low and high to rows or series (Error bars).

js
new GroupedBarChart(el, {
  data: {
    categories: ['Q1', 'Q2', 'Q3'],
    series: [
      { name: '2025', values: [120, 135, 150] },
      { name: '2026', values: [140, 160, 172] },
    ],
  },
});

The rest

Chartdata
Scatter · Bubble[{ x, y, size?, group?, label? }] — Scatter's size is the point radius in px; Bubble's size is a value drawn as the bubble's area
Heatmap{ x: [...], y: [...], values: [[...], …] } — values[y][x]
Boxplot[{ label, min, q1, median, q3, max, outliers? }]
Waterfall[{ label, value, total? }] — a total: true bar goes from zero to its value (subtotals, the end result)
Gaugea number (data: 72)
Realtime{ series: [{ name }] } — values arrive with push()
Candlestick[{ label, open, high, low, close }]
Treemap · Sunburstone value per item; a row with children: [...] nests — Hierarchies
Sankey{ links: [{ source, target, value }], nodes?: [{ id, label?, color? }] }
Network{ nodes: [{ id, label?, group?, size? }], links: [{ source, target, value? }] }
Mapone value per item (the label is the region id), plus the map as the geo option — Map

It tells you what's wrong

A wrong option or a data shape the chart can't read never turns into a silent empty chart. The browser console says what is wrong and how to fix it, once per message.

text
[aeriz] BarChart: unknown option "dat" — did you mean "data"?
[aeriz] BarChart: "color" is a 1.x option. In 2.0 use colors.
[aeriz] MultiLineChart: data must be { categories: [...], series: [{ name, values: [...] }] } — got an array.
[aeriz] MultiLineChart: series[1] "Sign-ups" has 5 values but there are 6 categories.
[aeriz] LineChart: rows need a "value" field, or pass value: (row) => row.amount.
[aeriz] PieChart: values can't be negative — "Refunds" is -3. It is drawn as 0.
[aeriz] BarChart: "zoom" is not available on this chart — it works on LineChart, MultiLineChart, AreaChart, CompositeChart, CandlestickChart and ScatterChart.
[aeriz] MapChart: 3 rows match no region (e.g. "Korea"). Keys are feature ids, or properties.name when a feature has no id.

Calling a removed method throws with its replacement (chart.setData() was removed. Use chart.update({ data }).). With TypeScript, the editor catches the same mistakes first.

Import only what you use

Every chart is its own module and the package has "sideEffects": false, so bundlers (Vite, webpack, Rollup, esbuild) drop the charts you don't use. Import as usual — also from the React, Vue and Svelte adapters.

js
import { BarChart, PieChart } from '@aeriz/chart'; // just these two plus the shared core

Without a bundler, or to be sure you get exactly one chart, import its subpath.

js
import { BarChart } from '@aeriz/chart/bar';
import { SparklineChart } from '@aeriz/chart/sparkline';
ImportSize (min + gzip)
One chart without axes (Gauge, Pie, Funnel …)about 12 KB
One hierarchy, flow or map chart (Treemap, Sunburst, Sankey, Network, Map)about 12–13 KB
One chart with axes (Bar, Line, Composite …)about 14–17 KB
Bar + Line + Pieabout 18 KB
All 26 typesabout 35 KB (the CDN aeriz.min.js is about 38 KB)
Zoom · sync (loaded separately the first time zoom or sync is used)about 3 KB
Tooltip links, buttons and custom content (loaded separately the first time tooltip: { … } is used)about 2.4 KB
React · Vue · Svelte · jQuery adapters0.3–0.7 KB each

Measured with esbuild. The shared core (canvas, theme, tooltip, legend, input, mistake warnings) is shared by every chart, so adding charts adds little.

Subpaths: bar hbar line area stacked-bar grouped-bar multi-line scatter bubble pie radar polar gauge heatmap boxplot funnel treemap sparkline realtime waterfall composite candlestick sunburst sankey network map

Vanilla JS

All five environments use the same chart names and options. Without a framework, use the classes directly.

js
import { LineChart } from '@aeriz/chart';

const chart = new LineChart('#trend', { data: [3, 7, 4, 9, 6, 12] });
chart.update({ data: [5, 8, 6, 11] });
chart.destroy(); // when the element leaves the page

React

Import the component with the chart's name from @aeriz/chart/react. Every option is a prop. Works with React 16.8 and later.

jsx
import { useRef } from 'react';
import { BarChart } from '@aeriz/chart/react';

export function Sales({ rows }) {
  const chart = useRef(null); // chart.current = the chart instance
  return (
    <BarChart
      data={rows}
      format={{ style: 'currency', currency: 'USD' }}
      onClick={(hit) => console.log(hit.label, hit.value)}
      ref={chart}
      style={{ height: 320 }}
    />
  );
}
  • Changed props call update(). Inline objects and functions re-created on every render don't redraw when their values are the same.
  • Arrays are compared by reference. Pass a new array to change data ([...rows, row]).
  • className, style, id, aria-* and data-* go to the wrapper <div>. StrictMode still creates one chart.

Vue

Import the component with the chart's name from @aeriz/chart/vue. Options are props; onClick, onHover, onLegend and onZoom are the events @click, @hover, @legend and @zoom. Works with Vue 3.2 and later.

vue
<script setup>
import { ref } from 'vue';
import { LineChart } from '@aeriz/chart/vue';

const rows = ref([3, 7, 4, 9]);
const add = () => (rows.value = [...rows.value, Math.random() * 10]);
const trend = ref(null); // trend.value.chart = the chart instance
</script>

<template>
  <LineChart :data="rows" curve="linear" @click="(hit) => console.log(hit)" ref="trend" style="height: 300px" />
</template>

Vue's reactive proxies are removed before the data reaches the chart, so large data stays fast. Replace data with a new value; changes made in place (rows.value.push()) are not detected.

Svelte

@aeriz/chart/svelte has one action per chart (barChart, lineChart, multiLineChart …). The parameter is the options. No compiler setup, and the same in Svelte 3, 4 and 5.

html
<script>
  import { barChart, chartOf } from '@aeriz/chart/svelte';

  let rows = $state([{ label: 'A', value: 5 }, { label: 'B', value: 9 }]);
</script>

<div use:barChart={{ data: rows, onClick: (hit) => console.log(hit) }} style="height: 300px"></div>

Use chartOf(element) when you need the chart instance.

jQuery

Add the charts you use with install($, { … }), then create one by its subpath name ('bar', 'pie' …). The CDN script (aeriz.min.js) adds all 26 by itself when jQuery is loaded first.

js
import $ from 'jquery';
import { PieChart } from '@aeriz/chart/pie';
import { install } from '@aeriz/chart/jquery';

install($, { PieChart });
$('#share').aerizChart('pie', { data: { Chrome: 64, Safari: 19 }, innerRadius: 0.6 });
js
$('#share').aerizChart('update', { data: { Chrome: 70, Safari: 20 } }); // setState · render · destroy work the same way
$('#share').aerizChart('instance');                                       // the chart instance

These are live. Click a legend item to turn a series off and on.

MultiLineChart
StackedBarChart
PieChart · innerRadius
CompositeChart · right axis
RadarChart
HeatmapChart
TreemapChart · children
WaterfallChart
GaugeChart
CandlestickChart
SunburstChart
SankeyChart
ClassSubpathdataNotes
BarChartbarone value per itemnegatives grow down, dataLabels
HBarCharthbarone value per itemhorizontal, label column fits the labels
LineChartlineone value per itemcurve, time axis, log axis, a million points, zoom, bands
AreaChartareacategories · seriesstacked ('percent'), zoom
StackedBarChartstacked-barcategories · seriesnegatives stack down, stacked: 'percent'
GroupedBarChartgrouped-barcategories · seriesseries side by side, error bars
MultiLineChartmulti-linecategories · seriesshared tooltip that follows the pointer, zoom, bands
ScatterChartscatter[{ x, y }]batched by color and size, zoom
BubbleChartbubble[{ x, y, size }]size is the area
PieChartpieone value per itemdonut with innerRadius, toggle slices from the legend
RadarChartradarcategories · seriestooltip per point
PolarChartpolarone value per itemarea follows the value (scale: 'linear' for radius)
GaugeChartgaugea numberupdate({ data }) moves on from the shown value
HeatmapChartheatmap{ x, y, values }colors: { low, high }
BoxplotChartboxplot[{ min, q1, median, q3, max }]outlier dots
FunnelChartfunnelone value per itemconversion from the first stage
TreemapCharttreemapone value per item (+ children)squarified layout; groups get a header
SparklineChartsparklineone value per itemtiny trend line, no axes
RealtimeChartrealtime{ series } + push()scrolls through a fixed window
WaterfallChartwaterfall[{ label, value, total? }]running total
CompositeChartcompositecategories · series (type)mix bars, lines, areas, dots; several value axes, stacked bars, zoom
CandlestickChartcandlestick[{ label, open, high, low, close }]price-fitted axis, zoom, tens of thousands of candles
SunburstChartsunburstone value per item (+ children)one ring per level, share in the middle
SankeyChartsankey{ links, nodes? }flow bands as thick as their value
NetworkChartnetwork{ nodes, links }force layout, neighbor highlight
MapChartmapone value per item + geocolors GeoJSON regions, scale: 'log'

Candlestick

Draws open, high, low and close for each period. The body runs from open to close (colors.up when the price rose, colors.down when it fell) and the wick from low to high. The value axis fits the visible prices instead of starting at zero.

js
new CandlestickChart('#stock', {
  data: candles,                   // [{ label, open, high, low, close }]
  zoom: true,
  range: ['7/29', '10/22'],        // start on the last three months
  annotations: [{ y: 80, label: 'Target $80' }],
  // colors: { up: '#ef4444', down: '#3b82f6' } for markets where red means up
});

Drag to zoom in; hold Shift and drag, or scroll sideways, to pan. Double-click to see everything.

When candles get thinner than 3 px only the wicks are drawn, and the pointer finds the nearest candle per pixel column, so tens of thousands of candles stay light. The x axis takes labels ('8/3') or xScale: 'time' with ms timestamps. An open or close outside low–high is reported in the console.

Hierarchies — treemap · sunburst

TreemapChart and SunburstChart take the same data. A row with children becomes a group, and a group's value is the sum of its children. There is no depth limit.

js
const budget = [
  { label: 'Engineering', children: [{ label: 'Backend', value: 42 }, { label: 'Apps', value: 30 }, { label: 'Data', value: 18 }] },
  { label: 'Marketing', children: [{ label: 'Ads', value: 25 }, { label: 'Events', value: 9 }, { label: 'Content', value: 7 }] },
  { label: 'Operations', children: [{ label: 'Support', value: 14 }, { label: 'Office', value: 8 }] },
  { label: 'Other', value: 6 },
];
new TreemapChart('#budget-tree', { data: budget, onClick: (hit) => console.log(hit.path) }); // ['Engineering', 'Backend']
new SunburstChart('#budget-sun', { data: budget });
TreemapChart · children
SunburstChart
  • The treemap gives each group a header with its name and total, and lays the children out inside it. Flat data with no children ({ JS: 42, TS: 30 }) draws exactly as in 2.0.
  • The sunburst puts the first level on the inner ring, and each child sits inside its parent's angle. Hovering a slice keeps only that branch bright and shows its share of the whole in the middle.
  • The tooltip shows the path from the top (Engineering › Backend: $42M), and onClick gets the same path as hit.path.

Flows — sankey

Draws the flow between stages as bands as thick as their value. Nodes come from the links, and each node sits as many columns to the right as its longest path from a start. Nodes with no outgoing flow end in the last column.

js
new SankeyChart('#journey', {
  data: {
    links: [
      { source: 'Search', target: 'Product page', value: 520 },
      { source: 'Ads', target: 'Product page', value: 300 },
      { source: 'Product page', target: 'Cart', value: 410 },
      { source: 'Cart', target: 'Purchase', value: 330 },
      // …
    ],
    nodes: [{ id: 'Purchase', color: '#10b981' }], // only to change a label or color
  },
});

A link that loops back (a cycle) can't be drawn in a sankey, so it is left out and the console names it. Hovering a band or a node highlights its flow, and onClick's hit.row is the link row (the node row for a node).

Relations — network

Places nodes and links with a force layout: links pull their ends together and nodes push each other apart, settling over the first second. animate: false and render() draw the settled layout at once.

js
new NetworkChart('#services', {
  data: {
    nodes: [{ id: 'web', group: 0 }, { id: 'gateway', group: 1, size: 120 }, …], // group: color, size: area
    links: [{ source: 'web', target: 'gateway', value: 80 }, …],               // value: width
  },
  radius: [4, 14], // radius in px of the smallest and the largest size
});

Hover a node to fade everything but its neighbors.

With 40 nodes or fewer every label is shown; with more, only the hovered node's neighborhood. New data through update() keeps the nodes that stay where they are, and only new nodes look for a place. A link that points to a missing node is reported in the console.

Map

Colors regions by value. The package ships no map data, so pass GeoJSON as geo. A region is found by its feature id, or by properties.name when it has no id.

js
const geo = await fetch('/data/world-110m.json').then((r) => r.json());

new MapChart('#world', {
  geo,                                          // FeatureCollection (Polygon · MultiPolygon, lon/lat)
  data: { KOR: 31846, JPN: 40247, USA: 65298 }, // region id → value (rows [{ label, value }] work too)
  scale: 'log',                                 // when values bunch up at one end (population, GDP …)
  format: { style: 'currency', currency: 'USD', notation: 'compact' },
});

GDP per person by country (2019, Natural Earth). The tooltip names each country from its properties.name.

  • Projections are projection: 'mercator' (default) and 'equirectangular'. The map is projected once per size, and the pointer follows the real shapes, holes and islands included.
  • Colors are colors: { low, high }; regions with no value are a pale gray. A color legend sits below the map (legend: false hides it).
  • When rows match no region, the console says how many and gives an example (check for "Korea" where "KOR" was meant). labelFormat: (id) => name renames regions in the tooltip.
  • The world map in these examples is world-110m.json (41 KB gzip): Natural Earth 1:110m (public domain) rounded to 0.1°. Ids are ISO 3166-1 alpha-3 codes, and properties has the English name (name), the Korean name (ko) and GDP per person (gdp). Antarctica is left out.

Realtime data

push() a value into a RealtimeChart and it appears on the right; values beyond window drop off the left.

js
const rt = new RealtimeChart('#cpu', { data: { series: [{ name: 'CPU' }, { name: 'Memory' }] }, window: 120, max: 100 });
setInterval(() => rt.push([cpu(), memory()]), 100);

Big data

When a LineChart has far more points than pixels, it keeps only the minimum and maximum of each pixel column. The shape stays the same and tooltips show the original points. The result is reused until the data changes, so moving the mouse doesn't recompute it.

Press the button to generate the data and time the draw.

Reference lines · targets · bands

Charts with a value axis draw lines and bands from annotations. A single value is a dashed line; [from, to] is a band. y sits on the value axis and x on the x axis (labels, time or numbers).

js
new LineChart('#latency', {
  data: latency, // response time per hour
  annotations: [
    { y: 300, label: 'SLO 300 ms', color: '#ef4444' }, // target line
    { y: [80, 160], label: 'Normal range' },          // band
    { x: '14:00', label: 'Deploy' },                  // vertical reference line
  ],
});
  • Taken by Bar, HBar, Line, Area, StackedBar, GroupedBar, MultiLine, Scatter, Bubble, Boxplot, Waterfall, Composite, Candlestick and Realtime (y only). Other charts say so in the console.
  • Lines and bands on the value axis stay visible, widening the axis if needed. A label sits above the right end of a horizontal line (under it when the line is at the top) and at the top of a vertical one; color is used for the line, the band and the text (a faint text color by default).
  • HBarChart's value axis is horizontal, so x is the value and y the item label. CompositeChart picks the value axis of a line with axis (More value axes).
  • update({ annotations }) redraws just the lines, without animation.

Zoom · pan · brush

With zoom: true the x axis can be zoomed and panned. LineChart, MultiLineChart, AreaChart, CompositeChart, CandlestickChart and ScatterChart take it. When zoomed, the value axis fits the visible data (axes with bars or areas start at zero).

js
const chart = new LineChart('#visits', {
  data: visits,                           // [{ label: time (ms), value }]
  xScale: 'time',
  zoom: true,
  range: [from, to],                      // the range to start with (all when left out)
  onZoom: (range) => console.log(range), // [from, to] or null, whenever the user changes it
});

chart.update({ range: null }); // show everything from code

Drag across the chart.

Mouse · trackpadTouchKeyboard (chart focused)
Zoom indrag to pick a range · Ctrl/⌘ + wheel · pinchspread two fingers+
Zoom outCtrl/⌘ + wheel · pinchpinch two fingers-
PanShift + drag · scroll sidewaysone-finger drag once zoomed inShift + ← →
Resetdouble-click · the top-right buttonthe top-right button0

A plain wheel scrolls the page, and a one-finger drag on a chart that isn't zoomed shows the tooltip, so page scrolling is never blocked. range is in x-axis units: ['Mar', 'May'] on a label axis, ms on a time axis, numbers on a number axis (Scatter). range without zoom just shows that range.

Light by default The code for dragging, pinching and sync (about 3 KB) loads separately, the first time a chart with zoom or sync is created. Charts that don't zoom never load it.

Brush

A chart with zoom: 'brush' always shows everything, and the range you drag on it is shown zoomed in by the charts in the same sync group. Drag an edge of the selection to resize it, or its inside to move it.

js
new LineChart('#detail', { data, xScale: 'time', sync: 'traffic' });
new LineChart('#overview', { data, xScale: 'time', sync: 'traffic', zoom: 'brush', range: [from, to] });

Synced charts

Charts with the same sync name share the crosshair and the zoom range. They match the same x value (label, time or number), so the chart types and data lengths can differ.

js
new MultiLineChart('#requests', { data: requests, sync: 'ops', zoom: true });
new AreaChart('#errors', { data: errors, sync: 'ops', zoom: true, stacked: true });
new CompositeChart('#cost', { data: cost, sync: 'ops', zoom: true });

Hover one chart, or drag on it to zoom, and the other two follow.

  • Only the chart under the pointer shows a tooltip. The others show a crosshair at the same spot (MultiLine · Composite), or a dashed line and the nearest item highlighted (the rest).
  • A chart that joins a group later starts at the group's current range; one that joins with its own range hands it to the group. update({ sync: null }) leaves the group.
  • onZoom runs only on the chart the user touched, so handle it once per group.

Stacking · 100% stacking

stacked: 'percent' scales each item's total to 100% and stacks the shares. The value axis runs 0–100%, and the tooltip shows the share next to the original value.

js
new StackedBarChart(el, { data, stacked: 'percent' }); // default true (values as they are)
new AreaChart(el, { data, stacked: 'percent' });       // true · false · 'percent'
new CompositeChart(el, { data, stacked: true });       // bars on the same axis ('percent' works too)
StackedBarChart · stacked: 'percent'
AreaChart · stacked: 'percent'

100% stacking is a share of positive values, so negatives count as 0 and the console says so. StackedBarChart always stacks, so its stacked takes only true (default) and 'percent'.

Error bars · confidence bands

Add low and high to a row and bars get an error bar, lines a band. Series data takes low and high arrays with one entry per value. The value axis widens to show the whole interval, and the tooltip reads value (low – high).

js
new BarChart(el, { data: [{ label: 'A', value: 0.031, low: 0.027, high: 0.035 }, …] });
new LineChart(el, { data: forecast }); // [{ label, value, low, high }] → line + band

new GroupedBarChart(el, {
  data: { categories, series: [{ name: '2026', values, low: [...], high: [...] }] },
});
BarChart · error bars
LineChart · forecast band

BarChart and LineChart take them on rows; GroupedBarChart, MultiLineChart and CompositeChart on series (Composite draws error bars on bars and dots, bands on lines and areas). Other charts say in the console that they leave them out.

More value axes · stacked combo

Give a CompositeChart series an axis name and each name gets its own value axis. 'left' (default) is on the left; other names go on the right in the order they appear, and series with the same name share an axis. stacked stacks the bars on the same axis.

js
new CompositeChart('#business', {
  stacked: true,
  data: {
    categories: ['Jan', 'Feb', 'Mar', …],
    series: [
      { type: 'bar', name: 'Online', values: online },  // left axis
      { type: 'bar', name: 'Store', values: store },    // same axis, so it stacks on top
      { type: 'line', name: 'Margin', values: margin, axis: 'margin', format: { style: 'percent' } },
      { type: 'line', name: 'Visitors', values: visitors, axis: 'visitors' },
    ],
  },
});
  • With several axes, an axis that holds just one series colors its tick labels like that series, so you can tell which line it belongs to.
  • An axis formats its numbers with its series' format. min and max apply to the left axis; the others fit their data.
  • 2.0's axis: 'right' works as before — 'right' is just another name.

Events at a glance

Every chart event is a function you pass as an option. There are no event-name strings and no addEventListener, and all 26 types use the same names and arguments. Swap a function any time with update({ onClick }); that doesn't replay the animation.

OptionCalled whenUse it for
onClick(hit, chart)an item is clicked, or Enter is pressed on the focused chartopening a detail page, a popup, drill-down
onHover(hit, chart)the item under the pointer changes; hit is null when it leavesa side panel, highlighting the same row in a table
onLegend(index, visible, chart, event)a legend item is clicked, before it changesevent.preventDefault() and do something else instead of the toggle
onZoom(range, chart)the user changes the rangekeeping the range in the URL, lining up other views — zoom
tooltip.actions(hit, chart)a tooltip is made (once per item)links and buttons under the tooltip
tooltip.render(hit, chart)a tooltip is made (once per item)your own tooltip content

hit has the same shape everywhere: index (position in your data), label, value, series (series index), row (the item you passed in) and, for hierarchies, path (the names from the top). Anything else you keep on a row, such as an id, is on hit.row. The names are the same in every framework.

js
new BarChart(el, { data: rows, onClick: open, onHover: show, tooltip: { actions } });

In React, passing a new function or tooltip object on every render doesn't redraw the chart.

Links and buttons in tooltips

The list tooltip.actions returns goes under the tooltip. An entry with href is a link; one with only onClick is a button. A click runs onClick(hit, chart, event) first, then the tooltip closes. Open a popup, a side panel or another page from that function.

js
new HeatmapChart('#orders', {
  data: { x: hours, y: days, values },             // orders by weekday × hour
  tooltip: {
    actions: (hit) => [
      { label: 'Orders', href: `/orders?day=${hit.row.y}&hour=${hit.row.x}` },
      { label: '8-week trend', onClick: (hit) => openTrend(hit) }, // a modal, a panel … anything
    ],
  },
});

Point at a cell, then move the mouse to a button in the tooltip. Crossing other cells on the way doesn't move the tooltip.

  • Apps with a router Keep the href (for new tabs and copying the address), and in onClick call event.preventDefault(), then router.push(href).
  • New tab target: '_blank'. rel="noopener" is added for you.
  • Blocked javascript: addresses are blocked, and the console says to use onClick.

A tooltip that waits for the mouse

A tooltip with links or buttons waits for the mouse to reach it. There is nothing to set, and tooltips without links or buttons follow the mouse right away, as before.

  • On the way — while the mouse moves toward the tooltip, the items it crosses are skipped. If it rests for 0.3 s on the way, the item under it takes over.
  • Leaving — leaving the chart or the tooltip closes it after 0.3 s, so slipping out for a moment is fine.
  • Keyboard — pick an item with ← → and its tooltip opens; Tab moves into its links and buttons. Esc closes the tooltip and goes back to the chart.
  • Touch — a tap opens the tooltip, and its buttons can be tapped right away. A tap elsewhere closes it.
  • Screen readers — a tooltip with links or buttons becomes a region they can read and use; one without them is read by the chart, as before.

Your own tooltip content

What tooltip.render(hit, chart) returns becomes the tooltip. It runs once per item and isn't called again while the mouse stays on that item. With actions as well, the links and buttons go under your content.

ReturnTooltip
a string or numberthat text (never parsed as HTML)
a DOM nodethat node as it is. With a link or button inside, it becomes a tooltip that waits for the mouse
nullno tooltip for this item
undefinedthe usual tooltip
js
const card = document.querySelector('#store-card');       // a <template>

new BarChart('#stores', {
  data: stores,                                            // [{ label, value, target, manager }]
  tooltip: {
    render: (hit) => {
      const el = card.content.firstElementChild.cloneNode(true);
      el.querySelector('.name').textContent = hit.label;    // data goes in as textContent
      el.querySelector('.meter i').style.width = `${(hit.value / hit.row.target) * 100}%`;
      return el;
    },
    actions: (hit) => [{ label: 'Store page', href: `/stores/${hit.row.id}` }],
  },
});

Point at a bar to see its store card.

  • Strings Always shown as text, so tags in your data are harmless.
  • HTML Return a DOM node. Cloning a <template> and filling it with textContent works well. An HTML string shows as plain text, and the console says to return a node.
  • Colors Background and text color follow the theme (--aeriz-tooltip-bg · --aeriz-tooltip-fg).

Click to drill down

Call update({ data }) from onClick and you have a drill-down. The new data animates in, and Enter does the same from the keyboard.

js
const chart = new BarChart('#sales', {
  data: regions,                         // [{ label: 'West', value: 412, children: [...] }, ...]
  onClick: (hit) => {
    if (hit.row.children) chart.update({ data: hit.row.children });
  },
});

Click a bar to go from region to city to store; click the path above to go back.

Legend events

A legend click calls onLegend(index, visible, chart, event) before anything changes.

  • visible — the state the item is about to get by default. true for the last visible one, which can't be hidden.
  • event.preventDefault() — stops the default hide/show.
  • event.target — the legend button that was clicked.

The hidden option (the positions of the legend items to hide) says what is hidden. Set it from the start or with update({ hidden }); legend clicks update chart.options.hidden too, so you can save it and open the chart the same way next time.

js
new MultiLineChart('#traffic', {
  data: { categories, series },
  hidden: [3],                                    // start with the fourth series hidden
  onLegend: (i, visible, chart, event) => {
    event.preventDefault();                       // instead of hide/show: show only this one, click again for all
    const others = series.map((_, j) => j).filter((j) => j !== i);
    const alone = String(chart.options.hidden) === String(others);
    chart.update({ hidden: alone ? [] : others });
  },
});

To open a menu at the legend item, use the position of event.target. In the demo below a legend click opens a menu, and the menu changes hidden. The menu is the browser's popover, so a click outside or Esc closes it.

js
onLegend: (i, visible, chart, event) => {
  event.preventDefault();
  const r = event.target.getBoundingClientRect();  // the legend button
  menu.style.left = `${r.left}px`;
  menu.style.top = `${r.bottom + 4}px`;
  menu.showPopover();                             // <div popover> … </div>
},

Click the legend: a menu opens instead of the hide/show. From the keyboard, Tab to the legend and press Enter.

Your own legend

Turn the built-in legend off with legend: false, build the legend you want and connect it to update({ hidden }): a list with values and shares, checkboxes, table rows. Add onHover and the item under the pointer can light up in your legend too.

js
const chart = new PieChart('#share', {
  data: browsers, colors, innerRadius: 0.6, legend: false,
  onHover: (hit) => highlight(hit?.index),        // hit is null when the pointer leaves
});

list.onclick = (e) => {
  const i = +e.target.closest('button').dataset.i;
  const hidden = chart.options.hidden ?? [];
  chart.update({ hidden: hidden.includes(i) ? hidden.filter((j) => j !== i) : [...hidden, i] });
};

    Click the list on the right to hide and show. Point at a slice and its row lights up.

    Follow what the pointer is on

    onHover(hit, chart) runs once each time the item under the pointer changes, and with null when the pointer leaves the chart. Mouse, touch and keyboard (← →) behave the same. Use it to show details in a side panel instead of a tooltip, to highlight the same row in a table, or to line up other views.

    js
    new CompositeChart('#revenue', {
      data: { categories: months, series: [thisYear, lastYear] },
      tooltip: false,                                 // a side panel instead of the tooltip
      onHover: (hit) => (hit ? showMonth(hit.index) : showYear()),
    });

    Move the mouse over the chart. Leave it and the panel goes back to the year's total.

    • Crosshair charts (MultiLine, Composite, Realtime) point at one place on the x axis, so their hit has only index and label. Read the values from your data by index.
    • Among charts tied with sync, only the chart the user points at calls onHover; the crosshairs that follow it don't.

    Theme

    Without any setup the chart reads the text color, font and background of its element and derives grid and axis colors from them. So charts fit light and dark pages as they are, and re-read the theme when the OS switches dark mode. Override only what you want with CSS variables.

    css
    .dashboard {
      --aeriz-color-1: #64c8ff;   /* palette: --aeriz-color-1 … 12 */
      --aeriz-color-2: #10b981;
      --aeriz-text: #e7eef5;       /* default: the element's color */
      --aeriz-grid: rgba(100, 200, 255, 0.08);
      --aeriz-font: 'Inter', sans-serif; /* default: the element's font-family */
      --aeriz-font-size: 12px;
      --aeriz-line-width: 2;
      --aeriz-bar-radius: 4;
      --aeriz-tooltip-bg: rgba(0, 0, 0, 0.9);
    }

    If a script changes the variables, call chart.render(). To recolor one chart, use the colors: ['#f00', '#0f0'] option. To color a single bar, put color on its row.

    VariableDefault
    --aeriz-textthe element's text color
    --aeriz-muted · --aeriz-grid · --aeriz-axisthe text color at 62% · 9% · 30%
    --aeriz-bgthe nearest opaque background
    --aeriz-font · --aeriz-font-sizethe element's font · 11
    --aeriz-accent#64c8ff (loading spinner)
    --aeriz-line-width · --aeriz-point-radius · --aeriz-bar-radius2 · 3 · 3
    --aeriz-tooltip-bg · --aeriz-tooltip-fgdark background · white text
    --aeriz-surfacetransparent (canvas background)
    --aeriz-color-1 … 12the 8 PALETTE colors

    Number and label format

    format formats values (tooltips and the value axis); labelFormat formats labels (x-axis labels and tooltip titles). There are no per-axis format options.

    js
    { format: { style: 'currency', currency: 'USD' } }      // $1,234.00
    { format: { style: 'percent' } }                         // 0.25 → 25%
    { format: (v) => v.toFixed(1) + '°C' }                   // a function
    { labelFormat: (t) => new Date(t).getHours() + 'h' }     // time-axis labels
    • Defaults Tooltips use thousands separators, and axes shorten from 10,000.
    • Language Numbers follow the user's browser language (English 12K, Korean 1.2만). To pin one, pass a function: format: (v) => v.toLocaleString('en-US')
    • CompositeChart Takes a format per series, and the axis that series sits on uses it too.

    Legend · tooltip · keyboard

    • Legend — added automatically to charts with several series (and to pies). Clicking an item hides or shows that series and refits the axis. The last visible one can't be hidden. Hide the legend with legend: false; hidden: [1] starts with that item hidden. To do something else on a click, see Legend events.
    • Tooltip — mouse, touch and pen. A tap leaves the tooltip open until you tap elsewhere. Tooltips stay inside the chart. Turn them off with tooltip: false; for your own content and for links or buttons, see Your own tooltip content and Links and buttons in tooltips.
    • Keyboard — focus the chart, move with ← → ↑ ↓, jump with Home · End, press Enter for onClick and Esc to close. Tab moves into a tooltip's links and buttons. The value read is announced to screen readers.
    • Click — onClick(hit, chart) runs only when an item is clicked. hit has index, label, value, series (series index) and row (the item you passed in); hierarchies add path (the names from the top). The click that ends a zoom or brush drag doesn't count as an item click.
    js
    new BarChart(el, {
      data: rows,
      title: 'Sales by month',                 // the name screen readers read
      onClick: (hit) => openDetail(hit.row),
    });

    States · animation

    js
    chart.setState('loading', 'Loading…');
    chart.setState('error', 'Network error');
    chart.setState('empty');   // emptyText (default 'No data')
    chart.setState(null);      // close

    Empty data shows emptyText by itself and clears when data arrives. Animation starts when the chart scrolls into view, turns off with animate: false, and is always off for users with "reduce motion" turned on.

    Common options

    Every option has a default, so pass only what you need. Options for one chart type are under Chart options.

    OptionTypeDefaultDescription
    datadepends on the chart—see Data shapes
    titlestringthe chart type's namethe name screen readers read; Gauge shows it below the value
    colorsstring[]CSS variables or PALETTEthis chart's colors (an object for Heatmap and Waterfall)
    formatIntl options | (v) => stringbrowser languagenumber format for tooltips and the value axis
    labelFormat(label) => string—x-axis labels and tooltip titles (charts with axes)
    min · maxnumberfrom the datavalue-axis range (charts with axes, Gauge, Realtime)
    legendbooleanshown for several seriesfalse hides it
    hiddennumber[][]positions of the legend items to hide; legend clicks update it (charts with a legend) — Legend events
    tooltipboolean | { render?, actions? }truefalse turns it off. render: the content, actions: links and buttons — Custom content · Links and buttons
    animatebooleantrueanimate the first draw and changes
    emptyTextstring'No data'text when there is no data
    onClick(hit, chart) => void—an item was clicked or Enter was pressed
    onHover(hit | null, chart) => void—the item under the pointer changed; null when it leaves — Side panel
    onLegend(index, visible, chart, event) => void—a legend item was clicked, before it changes; event.preventDefault() keeps it as it is
    annotations{ x | y, label?, color?, axis? }[]—reference lines, target lines and bands (charts with a value axis) — Annotations
    zoomboolean | 'brush'falsezoom and pan, or a brush (Line, MultiLine, Area, Composite, Candlestick, Scatter) — Zoom
    range[from, to] | nulleverythingthe x range to show (the charts above, with or without zoom)
    onZoom(range, chart) => void—the user changed the range
    syncstring—share the crosshair and range with charts of the same name — Sync

    Methods

    MethodReturnsDescription
    update(options)thismerges options (data included) and redraws with animation
    setState(state, text?)thisshows 'loading' · 'empty' · 'error'; null closes it
    render()thisre-reads CSS variables and draws the final frame now (off-screen, print, export)
    destroy()—removes listeners and observers and restores the element
    push(v | v[]) · clear()thisRealtimeChart only: add one sample (an array for several series) · remove all

    The package also exports Chart (extend it to write your own chart) and the default colors PALETTE. Nothing else.

    Chart options

    ChartOptions
    One-value-per-item chartslabel, value: functions that read a row ((row) => row.sales)
    BardataLabels: true or (value, row, index) => string. A row's low · high draw an error bar
    Linecurve: 'smooth' · 'linear' · 'step', xScale: 'category' · 'time', yScale: 'linear' · 'log', fill, points. A row's low · high draw a band
    MultiLinecurve, xScale
    Areastacked: true · false · 'percent'
    StackedBarstacked: true (default) · 'percent'
    Bubbleradius: [min, max] px (default [4, 32])
    PieinnerRadius: share of the radius 0–0.9 (0.6 = donut), center: center text or false
    Polarscale: 'sqrt' · 'linear'
    Radarmax (the outer ring's value)
    Gaugemin (0), max (100), unit
    Heatmapcolors: { low, high }
    Waterfallcolors: { up, down, total }
    Funnel · Treemap · SunburstlabelColor (#fff). Sunburst: center, the text in the middle, or false
    Sparklinefill, lastDot, min, max
    Realtimewindow (200), min, max
    Compositeper series type: 'bar' · 'line' · 'area' · 'scatter', axis: a value-axis name ('left' by default), format, low · high; on the chart xScale, stacked: true · 'percent'
    CandlestickxScale, colors: { up, down } (#10b981 · #ef4444)
    Networkradius: [min, max] px (default [4, 16])
    Mapgeo: GeoJSON, projection: 'mercator' · 'equirectangular', scale: 'linear' · 'log', colors: { low, high }, labelFormat: region names

    TypeScript types are included, so your editor shows each chart's options and data shape as you type.

    From 1.x to 2.0

    2.0 keeps one way to do each thing. When you use a 1.x name, the console tells you the new one, so open your pages and follow the warnings. To stay on 1.x, install npm install @aeriz/chart@1.

    js
    // 1.x
    new MultiLineChart(el, { categories, series, interpolation: 'linear', yTickFormat: (v) => v + '%' });
    chart.setData(rows);
    chart.setLoading('…');
    gauge.setValue(80);
    
    // 2.0
    new MultiLineChart(el, { data: { categories, series }, curve: 'linear', format: (v) => v + '%' });
    chart.update({ data: rows });
    chart.setState('loading', '…');
    gauge.update({ data: 80 });
    1.x2.0
    setData(d)update({ data: d })
    setLoading · setEmpty · setError · clearStatesetState('loading' | 'empty' | 'error' | null, text?)
    invalidate()render()
    Gauge setValue(v) · value · labelupdate({ data: v }) · data · title
    categories · series · layers · axes (options)data: { categories, series }
    Heatmap xLabels · yLabels · data: [{ x, y, value }]data: { x, y, values: [[…]] }
    Realtime series · windowSize · yMin · yMax · waitingTextdata: { series } · window · min · max · emptyText
    ariaLabeltitle
    palette · colorcolors
    colorLow/High · colorUp/Down/Totalcolors: { low, high } · colors: { up, down, total }
    yTickFormat · xTickFormatformat · labelFormat
    yLeftTickFormat · yRightTickFormatformat on each series
    interpolation ('step-after' …)curve: 'smooth' · 'linear' · 'step'
    yMin · yMaxmin · max (every chart with axes)
    minRadius · maxRadiusradius: [min, max]
    centerLabel: false · totalLabelcenter: false · center: 'text'
    Pie innerRadius: 80 (px) · 'auto'innerRadius: 0.6 (a ratio only)
    Waterfall isTotaltotal
    Scatter r · Bubble zsize
    Composite dots values: [{ x, y }]values: [value | null], like every series
    [['Jan', 64], …] pairs{ Jan: 64 } or [{ label, value }]
    SparklineSparklineChart
    onClick(hit, point, chart) (also called with null)onClick(hit, chart) (only on an item); hit.data → hit.row
    React · Vue <AerizChart type={BarChart} options={…} /><BarChart data={…} {…options} /> (from /react · /vue)
    Svelte use:aeriz={{ type: BarChart, … }} · onReadyuse:barChart={{ … }} · chartOf(node)
    jQuery install($) · .aerizChart(PieChart, …) · 'setData'install($, { PieChart }) · .aerizChart('pie', …) · 'update'
    getFPS · getActiveCount · scheduler · Engine · drawCartesian · toRows · mathnot exported (internal)