# nervure
> Animated SVG charts, maps, diagrams and dashboards for every JavaScript framework. 74 chart types, no dependency, MIT license. By Ali Ben Macha.
Install: `npm install nervure`. Use: `import { createChart } from 'nervure'; createChart(element, spec, options)`. The element must have a height.
A spec is one object with a `type`. Options: `theme`, `locale`, `animation` (false, or `{ speed, duration, delay, stagger, easing, effect, start }`), `toolbar` (export menu).
Types: xy, pie, radar, gauge, scatter, heatmap, timeline, treemap, pack, funnel, waterfall, tree, candlestick, ohlc, heikinashi, renko, violin, beeswarm, ridgeline, histogram, errorbar, boxplot, hexbin, lollipop, dumbbell, bullet, slope, bump, pareto, likert, population, marimekko, pictogram, waffle, progress, bars3d, stream, horizon, parallel, kpi, rose, radialbar, polar, chord, liquid, thermometer, speedometer, venn, sankey, arc, network, pipeline, tunnel, sunburst, icicle, dendrogram, flowchart, orgchart, mindmap, sequence, er, quadrant, fishbone, cycle, triangle, steps, events, hexmap, ternary, calendar, punchcard, wordcloud, triangles, map.
- [Everything in one file](https://nervure.benmacha.tn/llms-full.txt)
- [Gallery with code](https://nervure.benmacha.tn/charts/)
- [Frameworks](https://nervure.benmacha.tn/guide/frameworks): React, Next.js, Vue, Nuxt, Svelte, Angular, web component
- [Symfony and Laravel](https://nervure.benmacha.tn/guide/symfony-laravel)
- [CDN](https://nervure.benmacha.tn/guide/cdn)
- [Size and lazy loading](https://nervure.benmacha.tn/guide/size)
- [CSS](https://nervure.benmacha.tn/guide/css), [colours](https://nervure.benmacha.tn/guide/colours), [animation](https://nervure.benmacha.tn/guide/animation), [export](https://nervure.benmacha.tn/guide/export)
- [Live data](https://nervure.benmacha.tn/guide/live): polling, server-sent events, WebSocket; [server side](https://nervure.benmacha.tn/guide/server)
- [Maps of every country](https://nervure.benmacha.tn/maps/), [dashboards](https://nervure.benmacha.tn/guide/dashboards)
- [API, every field](https://nervure.benmacha.tn/api)
- [Comparison with other libraries](https://nervure.benmacha.tn/compare/)
- [MCP server, skill and plugin](https://nervure.benmacha.tn/ai/): `npx -y nervure`
- [Source](https://github.com/BenMacha/nervure)
# Charts
## Lines and bars
- [Line chart](https://nervure.benmacha.tn/charts/line-chart): Values that follow one another, joined by a line. Trends over time, two or three series compared.
- [Area chart](https://nervure.benmacha.tn/charts/area-chart): A line filled down to zero. One quantity whose total matters as much as its shape.
- [Step line](https://nervure.benmacha.tn/charts/step-line): A line that jumps from one value to the next. Prices, rates and stock levels that stay still between two changes.
- [Range band](https://nervure.benmacha.tn/charts/range-band): The space between a low and a high series. Forecasts with their uncertainty, daily low and high.
- [Bar chart](https://nervure.benmacha.tn/charts/bar-chart): One bar for each category. Comparing amounts side by side.
- [Horizontal bar chart](https://nervure.benmacha.tn/charts/horizontal-bar-chart): Bars that run to the right, with their names on the left. Rankings, and names too long for the bottom of a chart.
- [Grouped bar chart](https://nervure.benmacha.tn/charts/grouped-bar-chart): Several bars for each category. Comparing two or three series category by category.
- [Stacked bar chart](https://nervure.benmacha.tn/charts/stacked-bar-chart): Parts piled up into a total. A total and what it is made of.
- [Mixed chart with two axes](https://nervure.benmacha.tn/charts/mixed-chart-with-two-axes): Bars on one scale and a line on another. An amount and a rate in the same picture.
- [Logarithmic chart](https://nervure.benmacha.tn/charts/logarithmic-chart): A scale where each step multiplies by ten. Growth, and values that differ by thousands.
- [Sparkline](https://nervure.benmacha.tn/charts/sparkline): A line without axes, as small as a word. A trend inside a table or beside a figure.
- [3D bar chart](https://nervure.benmacha.tn/charts/3d-bar-chart): Isometric columns on a floor of rows and columns. A few values on two dimensions, when the picture has to strike.
## Shares
- [Pie chart](https://nervure.benmacha.tn/charts/pie-chart): Slices of a whole. Two to five shares that add up to a total.
- [Donut chart](https://nervure.benmacha.tn/charts/donut-chart): A pie with room for a figure in the middle. Shares, with their total in the hole.
- [Treemap](https://nervure.benmacha.tn/charts/treemap): Rectangles as large as their value. Many shares in little room.
- [Packed bubbles](https://nervure.benmacha.tn/charts/packed-bubbles): Circles gathered around the largest. Shares when their order matters more than their exact size.
- [Waffle chart](https://nervure.benmacha.tn/charts/waffle-chart): A hundred small squares shared between categories. Percentages that everybody can count.
- [Marimekko chart](https://nervure.benmacha.tn/charts/marimekko-chart): Stacked columns as wide as their total. Market size and market share together.
- [Sunburst chart](https://nervure.benmacha.tn/charts/sunburst-chart): Rings of slices, from the centre to the leaves. A hierarchy and the weight of each branch.
- [Icicle chart](https://nervure.benmacha.tn/charts/icicle-chart): A hierarchy in columns of blocks. Deep hierarchies, with names that can be read.
- [Venn diagram](https://nervure.benmacha.tn/charts/venn-diagram): Circles that overlap as much as their sets. What two or three groups have in common.
- [Pictogram](https://nervure.benmacha.tn/charts/pictogram): Small figures, each worth the same amount. Numbers of people or things, for a wide audience.
## Finance
- [Candlestick chart](https://nervure.benmacha.tn/charts/candlestick-chart): Open, high, low and close of each period, with volume and moving averages. Stock, currency and crypto prices.
- [OHLC bar chart](https://nervure.benmacha.tn/charts/ohlc-bar-chart): The four prices of a period on a thin bar. Prices over many periods, with less ink than candles.
- [Heikin-Ashi chart](https://nervure.benmacha.tn/charts/heikin-ashi-chart): Candles smoothed by the ones before them. Reading a trend without its noise.
- [Renko chart](https://nervure.benmacha.tn/charts/renko-chart): A brick each time the price moves by a fixed amount. Price moves, whatever the time they take.
## Distribution
- [Histogram](https://nervure.benmacha.tn/charts/histogram): How many values fall in each interval, with their density. The shape of a large sample.
- [Box plot](https://nervure.benmacha.tn/charts/box-plot): Median, quartiles, whiskers and outliers. Comparing several samples at a glance.
- [Violin plot](https://nervure.benmacha.tn/charts/violin-plot): The density of each sample, mirrored. Samples with more than one peak.
- [Beeswarm plot](https://nervure.benmacha.tn/charts/beeswarm-plot): Every value as a point, none over another. Small samples, where each value counts.
- [Ridgeline plot](https://nervure.benmacha.tn/charts/ridgeline-plot): Densities one above the other. How a distribution changes between groups or months.
- [Error bars](https://nervure.benmacha.tn/charts/error-bars): A value and its interval. Measures with their uncertainty.
- [Hexagonal bins](https://nervure.benmacha.tn/charts/hexagonal-bins): A cloud of points counted in hexagons. Thousands of points that would cover one another.
- [Scatter and bubble chart](https://nervure.benmacha.tn/charts/scatter-and-bubble-chart): Points on two axes, with a size and a group. The link between two measures.
- [Ternary plot](https://nervure.benmacha.tn/charts/ternary-plot): Three shares of a whole, in a triangle. Mixtures: soils, alloys, votes between three parties.
## Comparison
- [Lollipop chart](https://nervure.benmacha.tn/charts/lollipop-chart): A thin stem and a dot. Many categories with close values.
- [Dumbbell chart](https://nervure.benmacha.tn/charts/dumbbell-chart): Two values joined by a line. Before and after, men and women, plan and result.
- [Bullet chart](https://nervure.benmacha.tn/charts/bullet-chart): A value, its target and bands of quality. Goals, in the room of a line of text.
- [Slope chart](https://nervure.benmacha.tn/charts/slope-chart): Two columns joined by straight lines. What rose and what fell between two dates.
- [Bump chart](https://nervure.benmacha.tn/charts/bump-chart): Ranks over time. Who overtook whom.
- [Pareto chart](https://nervure.benmacha.tn/charts/pareto-chart): Bars from the largest, and their running share. Finding the few causes of most problems.
- [Likert chart](https://nervure.benmacha.tn/charts/likert-chart): Answers on both sides of a middle. Surveys with a scale of agreement.
- [Population pyramid](https://nervure.benmacha.tn/charts/population-pyramid): Two sets of bars back to back. Ages of men and women, imports and exports.
- [Progress bars](https://nervure.benmacha.tn/charts/progress-bars): How much of each goal is done. Tasks, quotas and levels.
- [Parallel coordinates](https://nervure.benmacha.tn/charts/parallel-coordinates): One line for each item, across several axes. Comparing items on many measures.
- [Waterfall chart](https://nervure.benmacha.tn/charts/waterfall-chart): Gains and losses between two totals. Explaining a profit, a budget or a head count.
- [Key figure](https://nervure.benmacha.tn/charts/key-figure): A figure, its change and its trend. The top of a dashboard.
## Time
- [Stream graph](https://nervure.benmacha.tn/charts/stream-graph): Layers that swell and shrink around a middle. How a mix changes over time.
- [Horizon chart](https://nervure.benmacha.tn/charts/horizon-chart): Many long series, each in a thin folded strip. Dozens of series on one screen.
- [Calendar heatmap](https://nervure.benmacha.tn/charts/calendar-heatmap): A square for each day. Habits and activity over a year.
- [Gantt chart](https://nervure.benmacha.tn/charts/gantt-chart): Bars on a calendar. Plans, phases and bookings.
- [Event timeline](https://nervure.benmacha.tn/charts/event-timeline): Dates along a line. A history in a few moments.
## Circles and gauges
- [Radar chart](https://nervure.benmacha.tn/charts/radar-chart): Several criteria around a centre. Profiles of two or three items.
- [Nightingale rose chart](https://nervure.benmacha.tn/charts/nightingale-rose-chart): Petals of the same angle, as large as their value. Months, directions, and other things that turn.
- [Radial bar chart](https://nervure.benmacha.tn/charts/radial-bar-chart): Bars bent around a circle. A few percentages, with style.
- [Polar chart](https://nervure.benmacha.tn/charts/polar-chart): A line around a dial. Hours of the day, directions of the wind.
- [Chord diagram](https://nervure.benmacha.tn/charts/chord-diagram): Ribbons between the arcs of a circle. Exchanges between places, in both directions.
- [Gauge chart](https://nervure.benmacha.tn/charts/gauge-chart): One value on a half circle, with a target. A single goal.
- [Speedometer chart](https://nervure.benmacha.tn/charts/speedometer-chart): A needle over coloured zones. A value that is good, fair or bad.
- [Liquid gauge](https://nervure.benmacha.tn/charts/liquid-gauge): A vessel that fills, with a moving surface. Levels: tanks, batteries, goals.
- [Thermometer chart](https://nervure.benmacha.tn/charts/thermometer-chart): A column that rises in a tube. Temperatures and fundraising.
## Flows and networks
- [Sankey diagram](https://nervure.benmacha.tn/charts/sankey-diagram): Ribbons as wide as what flows through them. Money, energy or visitors from step to step.
- [Pipe chart](https://nervure.benmacha.tn/charts/pipe-chart): Pipes that narrow, leaks included, with a moving flow. A process that loses something on the way.
- [Funnel chart](https://nervure.benmacha.tn/charts/funnel-chart): Steps that shrink, with the share that remains. Conversion rates.
- [Tunnel chart](https://nervure.benmacha.tn/charts/tunnel-chart): Steps seen one inside the other. A funnel in little height.
- [Network graph](https://nervure.benmacha.tn/charts/network-graph): Nodes spread by forces, and their links. Who is linked to whom.
- [Arc diagram](https://nervure.benmacha.tn/charts/arc-diagram): Names on a line, joined by arcs. Links between things that have an order.
## Diagrams
- [Flowchart](https://nervure.benmacha.tn/charts/flowchart): Boxes and arrows, laid out for you. Processes and decisions.
- [Organisation chart](https://nervure.benmacha.tn/charts/organisation-chart): People or teams from the top down; branches fold. Who works with whom.
- [Mind map](https://nervure.benmacha.tn/charts/mind-map): Ideas that branch from a centre. Plans, lessons, notes of a meeting.
- [Sequence diagram](https://nervure.benmacha.tn/charts/sequence-diagram): Messages between actors, in order. Describing an exchange between programs.
- [Entity relationship diagram](https://nervure.benmacha.tn/charts/entity-relationship-diagram): Tables, their fields and their links. Documenting a database.
- [Radial tree](https://nervure.benmacha.tn/charts/radial-tree): A hierarchy around its root; branches fold. Wide trees in a square room.
- [Dendrogram](https://nervure.benmacha.tn/charts/dendrogram): A hierarchy from left to right. Classifications and families.
- [Quadrant chart](https://nervure.benmacha.tn/charts/quadrant-chart): Four zones and the points that fall in them. Priorities, SWOT, effort against value.
- [Fishbone diagram](https://nervure.benmacha.tn/charts/fishbone-diagram): Causes along the bones of a problem. Finding why something went wrong.
- [Cycle diagram](https://nervure.benmacha.tn/charts/cycle-diagram): Steps that come back to the first. Plan, do, check, act.
- [Pyramid diagram](https://nervure.benmacha.tn/charts/pyramid-diagram): Levels of a triangle. Needs, strategies, layers of a system.
- [Step diagram](https://nervure.benmacha.tn/charts/step-diagram): Arrows one after the other, done or to do. Where you are in a process.
## Grids
- [Heatmap](https://nervure.benmacha.tn/charts/heatmap): A colour for each row and column. Days and hours, products and regions.
- [Punch card](https://nervure.benmacha.tn/charts/punch-card): A circle for each row and column. When things happen.
- [Hexagon map](https://nervure.benmacha.tn/charts/hexagon-map): Hexagons as tiles, with their value. Maps where each place counts the same.
- [Triangle grid](https://nervure.benmacha.tn/charts/triangle-grid): Triangles up and down, as dark as their value. Many small values, as a pattern.
- [Word cloud](https://nervure.benmacha.tn/charts/word-cloud): Words as large as their weight. A first look at a text.
# Accessibility
- Each chart is an image with a text: its `title` and `description`, or a summary of the data. Write your own `description` for what the chart shows.
- Points, items and tree nodes that can be clicked take the focus and answer to Enter and Space.
- Charts do not move for people who ask for reduced motion.
- Text in shapes is black or white, whichever reads better.
- Colour is not always enough: add labels, or a table beside the chart.
## Safety
Names and categories are written as text, never parsed as HTML. `decorate` and colours come from your code: do not build them from what visitors type.
# Animation
## On or off
```ts
createChart(host, spec); // animated
createChart(host, spec, { animation: false }); // drawn at once
```
People who ask their system for less motion get no animation, whatever you write.
## When
```ts
createChart(host, spec, { animation: { start: 'load' } }); // at once, the default
createChart(host, spec, { animation: { start: 'visible' } }); // when the reader scrolls to it
const chart = createChart(host, spec, { animation: { start: 'manual' } });
button.onclick = () => chart.play(); // when you decide, as often as you want
```
The room of the chart is kept while it waits, so nothing on the page jumps.
## How
| Option | Does |
|---|---|
| `speed` | `2` is twice as fast |
| `duration` | milliseconds for each mark, instead of the timing of the chart |
| `delay` | milliseconds before the first mark |
| `stagger` | `false` moves every mark together |
| `easing` | any CSS easing, such as `cubic-bezier(.34,1.56,.64,1)` for a bounce |
| `effect` | `fade` replaces movement by a fade |
Charts use the Web Animations API of the browser: no timer runs once they are drawn. Only `liquid` and `pipeline` with `flow` move without end.
`chart.update(spec)` plays again; `chart.refresh(spec)` does not, for live data.
# CDN and plain HTML
```html
```
The web component is included:
```html
```
In production, name a version: the file never changes.
```html
```
Live data is included too: `nervure.live`, `nervure.poll`, `nervure.events`, `nervure.socket` and `nervure.append`, and so are `createDashboard`, `loadMap` and `sample`.
# Colours
A colour is found in this order: `setColor`, then the one in the spec, then the palette.
## Palette
```ts
createChart(host, spec, { theme: { palette: ['#30466b', '#d1495b', '#2a9d8f'] } });
```
## From code
```ts
chart.setPalette(['#264653', '#e76f51', '#2a9d8f']);
chart.setColor('Last year', '#b8b4ad'); // a series, a slice, a group, an item
chart.resetColors();
```
Try it with the colour pickers of the [editor](/editor).
## One point
```ts
{ name: 'Change', kind: 'bar', data: [42, -8], colors: [undefined, '#d1495b'] }
```
## Named themes
```ts
createChart(host, spec, { theme: 'dark' }); // or 'light', or 'auto' to follow the system
```
## Theme
```ts
const dark = { strong: '#f3f4f6', label: '#d1d5db', muted: '#9ca3af', grid: '#33383f', halo: '#1b1b1f', surface: '#1b1b1f' };
chart.update(spec, { theme: dark });
```
The stylesheet can set them too: see [CSS](/guide/css). CSS variables work (`color: 'var(--brand)'`) and are replaced by their value in exports.
# CSS
Every mark is an SVG element of the page: select it and style it. `toSVG` and `toPNG` keep what your stylesheet changed.
## Variables
```css
.report {
--nervure-palette: #264653, #e76f51, #2a9d8f;
--nervure-label: #333;
--nervure-muted: #777;
--nervure-grid: #eee;
--nervure-strong: #000;
--nervure-surface: #fff;
--nervure-halo: #fff;
--nervure-font: Inter, sans-serif;
}
@media (prefers-color-scheme: dark) { .report { --nervure-label: #ddd; --nervure-surface: #111; --nervure-halo: #111; } }
```
Call `chart.resize()` after you change a variable from code. The `theme` option wins over the stylesheet.
## What to select
| Selector | Is |
|---|---|
| `svg.nervure[data-type="sankey"]` | a chart, by type |
| `[data-part="axes"]` | grid, axis labels and titles |
| `[data-part="series"]` | every mark |
| `[data-part="legend"]`, `[data-part="legend-item"]` | the legend |
| `[data-part="heading"]`, `[data-part="subheading"]` | titles in the drawing |
| `[data-series="Last year"]` | the marks of a name |
| `[data-direction="up"]` | candles and bricks that rise |
| `.nervure-tooltip`, `.nervure-toolbar` | the tooltip and the export menu, in HTML |
| `.nervure-card`, `.nervure-card-title` | dashboards |
## Try it
# Your own chart
A chart type is three functions. It gets the theme, the tooltip, the animation, the exports and the accessibility of the others.
The type starts with `custom:`. If others could use it, [propose it](/contribute).
# Dashboards
```ts
import { createDashboard } from 'nervure/dashboard';
const board = createDashboard(host, {
link: true, // a series hidden in one chart is hidden in all
editable: true, // cards move with the mouse, or the arrow keys on their title
onMove: (ids) => localStorage.setItem('order', JSON.stringify(ids)),
items: [
{ id: 'revenue', title: 'Revenue', width: 8, height: 3, spec: revenue },
{ id: 'goal', title: 'Goal', width: 4, height: 3, spec: goal, options: { toolbar: true } },
],
});
board.update('goal', nextGoal);
board.add({ id: 'map', title: 'Map', width: 12, spec: map });
board.move('map', 0);
board.chart('revenue')?.download('png');
board.destroy();
```
| Option | Default | Does |
|---|---|---|
| `columns` | 12 | columns of the grid |
| `rowHeight`, `gap` | 110, 16 | pixels |
| `stackUnder` | 640 | under this width, one card by line |
| `theme`, `locale`, `animation`, `toolbar` | | given to every chart |
Cards are plain HTML: style `.nervure-dashboard`, `.nervure-card` and `.nervure-card-title`.
# Export
## A menu
`toolbar: true` adds a small button. It takes the formats, their labels, the name of the file, an icon, and what to write in the file.
## From code
```ts
await chart.download('png', 'orders', { title: 'Orders', subtitle: '2026', caption: 'Source: me', background: '#fff', padding: 24, scale: 3 });
const svg = chart.toSVG({ title: 'Orders' });
const png = await chart.toPNG({ scale: 2 });
const csv = chart.toCSV();
```
| Option | Does |
|---|---|
| `title`, `subtitle`, `caption` | text written in the file only |
| `background` | the theme in PNG, transparent in SVG |
| `padding` | pixels around the drawing |
| `scale` | PNG only, 2 by default |
Headings, notes, what `decorate` adds and what your CSS changed are kept; tooltips and buttons are not. PNG files use system fonts, because a browser does not load web fonts inside an image. Cells of a CSV that look like a formula get a quote in front.
# Frameworks
The host element must have a height, and the spec should be memoised: a new object draws the chart again.
## React
```tsx
import { useMemo, useRef } from 'react';
import { Chart } from 'nervure/react';
export function Orders({ rows }) {
const chart = useRef(null);
const spec = useMemo(() => ({
type: 'xy', categories: rows.map((r) => r.month),
series: [{ name: 'Orders', kind: 'bar', data: rows.map((r) => r.count) }],
}), [rows]);
return { chart.current = c; }} />;
}
```
## Next.js
The same component. `nervure/react` is already marked `'use client'`, so it can be imported from a server component as long as the spec holds no function.
```tsx
// app/page.tsx
import { Chart } from 'nervure/react';
export default async function Page() {
const data = await getOrders();
return ;
}
```
## Vue
```vue
{}" />
```
## Nuxt
```vue
```
## Svelte and SvelteKit
```svelte
```
## Angular
```ts
import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import 'nervure/element';
@Component({
selector: 'app-orders',
schemas: [CUSTOM_ELEMENTS_SCHEMA],
template: ``,
})
export class OrdersComponent {
spec = { type: 'funnel', data: [{ name: 'Visitors', value: 5200 }, { name: 'Customers', value: 310 }] };
}
```
## Solid, Astro, Lit, Ember, HTMX, plain HTML
Use the web component:
```html
```
From code, set the property: `element.spec = {…}`. It fires `ready`, with the chart in `event.detail`.
# Install
::: code-group
```bash [npm]
npm install nervure
```
```bash [pnpm]
pnpm add nervure
```
```bash [yarn]
yarn add nervure
```
```bash [bun]
bun add nervure
```
```bash [Deno]
deno add npm:nervure
```
```bash [From GitHub]
npm install github:BenMacha/nervure
```
:::
yarn, pnpm, bun and Deno read the npm registry: the package is the same everywhere. Without a bundler, use [one script tag](/guide/cdn).
React and Vue are optional: they are needed only by `nervure/react` and `nervure/vue`.
| Import | For |
|---|---|
| `nervure` | `createChart`, in any project |
| `nervure/react` | React, Next.js, Remix, Gatsby |
| `nervure/vue` | Vue 3, Nuxt |
| `nervure/svelte` | Svelte, SvelteKit |
| `nervure/element` | the `` web component, for Angular, Solid, Astro and plain HTML |
| `nervure/live` | live data |
| `nervure/server` | event streams on your server |
| `nervure/stimulus` | Symfony UX, Rails, Laravel |
| `nervure/dashboard` | dashboards |
| `nervure/maps` | map files |
| `nervure/lazy`, `nervure/core`, `nervure/charts/*` | [only what you draw](/guide/size) |
| `nervure/samples` | made-up data for each chart |
# Labels and notes
| Field | Writes |
|---|---|
| `heading`, `subheading` | text above the chart |
| `xTitle`, `axes[].title` | axis titles |
| `showLabel` | the value of each point or bar |
| `labels` | your own text for each value |
| `labelAngle` | turned category names |
| `format`, `axes[].format` | every number, or the numbers of one axis |
| `lines` | a target, an average, a date |
| `annotations` | a note on a point |
## From code
```ts
chart.addLine({ value: 60, label: 'Average' });
chart.addAnnotation({ at: 'Feb', value: 73, text: 'Holiday' });
chart.clearNotes();
```
## Your own elements
`decorate` receives the SVG: add a header or a watermark, which exports keep.
```ts
{ ...spec, insetTop: 40, decorate: ({ svg, width, theme }) => { /* append elements */ } }
```
# Live data
`live` feeds a chart from a source. It retries with growing waits after an error, stops while the tab is hidden, and draws at most ten times a second.
## Market price
```ts
import { append, live, poll } from 'nervure/live';
const spec = { type: 'xy', categories: [], series: [{ name: 'Price', data: [], dots: false }] };
const chart = createChart(host, spec);
const feed = live(chart, spec, poll('/api/price', { every: 1000 }), {
apply: (data, previous) => append(previous, data.time, { Price: data.price }, 60),
onStatus: (status) => console.log(status),
});
```
The figures on this page are made up in your browser.
## Processor and memory
## Sources
```ts
poll('/api/cpu', { every: 2000, init: { headers: { Authorization: `Bearer ${token}` } } }); // an API, every 2 s
poll(async (signal) => (await client.read({ signal })).value, { every: 5000 }); // your own function
events('/api/cpu/stream'); // server-sent events
socket('wss://example.com/prices', { hello: { subscribe: ['EURUSD'] } }); // WebSocket
```
| Source | Use it when |
|---|---|
| `poll` | you have a plain API; every few seconds is enough |
| `events` | your server pushes; one way, over plain HTTP, see [server side](/guide/server) |
| `socket` | many messages a second, or an existing WebSocket feed |
`poll` waits for an answer before it counts the next interval, so a slow API is never called twice at once.
## Control
```ts
feed.pause();
feed.resume();
feed.stop(); // call it when the chart goes away
feed.status; // connecting, live, paused, retrying or stopped
```
| Option | Default | Does |
|---|---|---|
| `apply` | | turns a message into the next spec; `null` ignores it |
| `throttle` | 100 | at most one drawing in this time (ms) |
| `retry` | 1 s to 30 s | waits after errors; `false` gives up |
| `pauseWhenHidden` | `true` | stops while the tab is hidden |
| `onStatus`, `onError` | | follow what happens |
## In React
```tsx
{
if (chart) feed.current = live(chart, spec, events('/api/cpu/stream'), { apply });
else feed.current?.stop();
}} />
```
::: warning Keep keys on your server
A key used in the browser can be read by everyone. Call paid or private APIs from your server, and let the chart read yours.
:::
# Maps
```ts
import { createChart } from 'nervure';
import { loadMap } from 'nervure/maps';
const geo = await loadMap('countries/tn');
createChart(host, { type: 'map', geo, values: { 'TN-11': 1056, 'TN-61': 955 }, legend: true, zoom: true });
```
## Files
| Path | Holds |
|---|---|
| `world`, `continents` | every country; every continent |
| `continents/africa` … | the countries of a continent |
| `countries/tn` … | the regions of a country, by its two-letter code |
| `france/departements`, `france/departements-outre-mer` | French departments |
| `france/communes/75` … | the municipalities of a department |
They are fetched from this site and kept in memory. To serve them yourself, copy the [maps folder](https://github.com/BenMacha/nervure/tree/main/maps) and give its address: `loadMap('world', '/maps')`. [Look at all of them](/maps/).
## Your own map
Any GeoJSON or TopoJSON works: pass it as `geo`, with `key` for the property that identifies a place and `nameKey` for its name.
## Projections
`mercator` (default), `equirectangular`, `naturalEarth` for the world, `conic` for a country far from the equator, `orthographic` for a globe that can be turned.
## Language
Maps hold `name`, `name_fr` and `name_ar`: `nameKey: 'name_ar'` shows Arabic names.
# Server side
`eventStream` calls your function every `every` milliseconds and sends what it returns. It answers with a Web `Response`, so it runs anywhere that speaks them. It stops when the visitor leaves.
## Next.js
```ts
// app/api/cpu/route.ts
import os from 'node:os';
import { eventStream } from 'nervure/server';
export const dynamic = 'force-dynamic';
export const GET = (request: Request) =>
eventStream(() => ({
time: new Date().toLocaleTimeString('en-GB'),
load: Math.round((os.loadavg()[0] / os.cpus().length) * 100),
}), { every: 1000, signal: request.signal });
```
In the browser: `events('/api/cpu')`.
## A paid API, with the key kept secret
```ts
export const GET = (request: Request) =>
eventStream(async (signal) => {
const r = await fetch('https://api.example.com/quote?symbol=ACME', { headers: { 'X-Api-Key': process.env.QUOTE_KEY! }, signal });
if (!r.ok) throw new Error(`HTTP ${r.status}`); // this message is skipped
return r.json();
}, { every: 5000, signal: request.signal });
```
Each visitor opens its own stream. With many visitors, read the API once, keep the answer, and send it to all.
## Other servers
::: code-group
```ts [Hono, Bun, Deno, Workers]
app.get('/stream', (c) => eventStream(read, { every: 1000, signal: c.req.raw.signal }));
```
```ts [SvelteKit]
export const GET = ({ request }) => eventStream(read, { every: 1000, signal: request.signal });
```
```ts [Nuxt]
export default defineEventHandler(() => eventStream(read, { every: 1000 }));
```
```ts [Astro]
export const GET = ({ request }) => eventStream(read, { every: 1000, signal: request.signal });
```
:::
PHP, Python, Go or any other language: send `text/event-stream` with one `data: {…}` line of JSON followed by an empty line, and `events()` reads it.
# Size and lazy loading
You ship what you draw. nervure has no dependency, and each chart is a module of its own.
## Pick your charts
```ts
import { createChart, registerChart } from 'nervure/core';
import { pie } from 'nervure/charts/basic/pie';
import { xy } from 'nervure/charts/basic/xy/index';
registerChart('pie', pie);
registerChart('xy', xy);
```
The rest never enters your bundle. The [source folder](https://github.com/BenMacha/nervure/tree/main/src/charts) lists the paths.
## Load when drawn
```ts
import { createChart, load } from 'nervure/lazy';
const chart = await createChart(host, spec); // fetches the code of its type, once
await load('sankey', 'map'); // ahead of time
```
Vite, webpack, Rollup, esbuild and Parcel make a small file of each type. Before you give another type to `chart.update`, call `load` for it.
## In a framework
`nervure/react`, `nervure/vue` and `nervure/svelte` hold every chart. `nervure/react/core`, `nervure/vue/core` and `nervure/svelte/core` hold none: register those you draw.
```tsx
import { registerChart } from 'nervure/core';
import { gauge } from 'nervure/charts/basic/gauge';
import { Chart } from 'nervure/react/core';
registerChart('gauge', gauge);
```
## While it runs
A chart that is drawn does nothing: no loop, no timer. Live charts stop in hidden tabs, and draw at most ten times a second.
# First chart
```ts
import { createChart } from 'nervure';
const chart = createChart(document.querySelector('#chart')!, {
type: 'xy',
categories: ['Jan', 'Feb', 'Mar', 'Apr'],
legend: true,
series: [
{ name: 'This year', data: [12, 18, 25, 31] },
{ name: 'Last year', data: [10, 14, 20, 24], dashed: true },
],
});
```
The host element must have a size; the chart follows it.
```css
#chart { height: 300px; }
```
## Change it
```ts
chart.update(nextSpec); // with the entrance animation
chart.refresh(nextSpec); // at once, for live data
chart.destroy(); // when you are done
```
## Options
```ts
createChart(host, spec, { locale: 'en-GB', animate: false, theme: { font: 'Inter, sans-serif' } });
```
# Symfony and Laravel
The `` web component needs no build tool and follows Turbo and Livewire: it cleans up when its element goes away.
## Symfony
### AssetMapper
```bash
php bin/console importmap:require nervure/element
```
```js
// assets/app.js
import 'nervure/element';
```
```php
#[Route('/orders')]
public function orders(OrderRepository $orders): Response
{
$rows = $orders->countByMonth();
return $this->render('orders.html.twig', ['spec' => [
'type' => 'xy',
'categories' => array_column($rows, 'month'),
'series' => [['name' => 'Orders', 'kind' => 'bar', 'data' => array_column($rows, 'count')]],
]]);
}
```
```twig
```
### A Twig component
```twig
{# templates/components/Chart.html.twig #}
{% props spec, height = 320, animation = 'visible' %}
```
```twig
```
### Stimulus and Symfony UX
```js
// assets/controllers/chart_controller.js
import { Controller } from '@hotwired/stimulus';
import { chartController } from 'nervure/stimulus';
export default chartController(Controller);
```
```twig
```
The controller draws again when its value changes, and dispatches `chart:ready` with the chart.
### Turbo and Mercure
A Turbo Frame or a Turbo Stream that replaces the element replaces the chart. For a chart that moves with your data, listen to Mercure:
```js
import { append, events, live } from 'nervure/live';
live(chart, spec, events('https://example.com/.well-known/mercure?topic=prices'), {
apply: (data, previous) => append(previous, data.time, { Price: data.price }, 60),
});
```
### Webpack Encore
`npm install nervure`, then the same imports.
## Laravel
### Vite and Blade
```bash
npm install nervure
```
```js
// resources/js/app.js
import 'nervure/element';
```
```blade
```
### A Blade component
```blade
{{-- resources/views/components/chart.blade.php --}}
@props(['spec', 'height' => 320])
merge(['style' => "height: {$height}px"]) }} spec="{{ json_encode($spec) }}">
```
```blade
```
### Livewire
```blade
```
```php
$this->dispatch('orders-changed', spec: $this->spec());
```
```js
Livewire.on('orders-changed', ({ spec }) => { document.querySelector('#orders').spec = spec; });
```
### Inertia
Use [the React, Vue or Svelte component](/guide/frameworks).
## Rails, Django, WordPress
The same web component, with [one script tag](/guide/cdn).
# Types
```ts
import type { MapCharts } from './specs/map.ts';
import type { GridCharts } from './specs/grid.ts';
import type { DiagramCharts } from './specs/diagram.ts';
import type { FlowCharts } from './specs/flow.ts';
import type { CircularCharts } from './specs/circular.ts';
import type { ComparisonCharts } from './specs/comparison.ts';
import type { DistributionCharts } from './specs/distribution.ts';
import type { FinanceCharts } from './specs/finance.ts';
export type * from './specs/finance.ts';
export type * from './specs/distribution.ts';
export type * from './specs/comparison.ts';
export type * from './specs/circular.ts';
export type * from './specs/flow.ts';
export type * from './specs/diagram.ts';
export type * from './specs/grid.ts';
export type * from './specs/map.ts';
/** Colours and fonts. Every field is optional when passed by the caller. */
export interface Theme {
strong: string;
label: string;
muted: string;
grid: string;
halo: string;
surface: string;
font: string;
/** Colours used when a series or a point has none. */ palette: string[];
}
/** A line across the chart: a target, an average, a date. */
export interface ReferenceLine {
value?: number;
/** Vertical line on a category (xy) or on the x axis (scatter). */ at?: string | number;
axis?: number;
label?: string;
color?: string;
dashed?: boolean;
}
/** A note pinned on the chart. `at` is a category (xy) or an x value (scatter). */
export interface Annotation {
at: string | number;
value: number;
text: string;
color?: string;
axis?: number;
}
export interface Series {
name: string;
data: (number | null)[];
color?: string;
kind?: 'line' | 'bar' | 'area' | 'band';
/** Lower bound of a `band` (`data` is the upper one). */
low?: (number | null)[];
/** Colour of one point or bar, when it differs from the series. */
colors?: (string | undefined)[];
dashed?: boolean;
gradient?: boolean;
dots?: boolean;
showLabel?: boolean;
/** Text of each label, instead of the formatted value. */
labels?: (string | undefined)[];
/** Joins points with straight segments (default), a smooth curve or steps. */
curve?: 'linear' | 'smooth' | 'step';
/** Index in `axes`. */
axis?: number;
legend?: boolean;
width?: number;
opacity?: number;
}
export interface Axis {
side?: 'left' | 'right';
/** `log` ignores zero and negative values. */ scale?: 'linear' | 'log';
min?: number;
max?: number;
title?: string;
format?: (value: number) => string;
}
export interface DecorateContext {
svg: SVGSVGElement;
width: number;
height: number;
theme: Theme;
}
export interface Base {
title?: string;
description?: string;
format?: (value: number, series?: string) => string;
/** Text written above the drawing (part of the exports). */
heading?: string;
subheading?: string;
/** Pixels kept free above the drawing, for a header added by `decorate`. */
insetTop?: number;
/** Pixels kept free under the drawing (a watermark). */
insetBottom?: number;
/** Adds your own elements (header, watermark); they are part of the exports. */
decorate?: (context: DecorateContext) => void;
}
export interface XYSpec extends Base {
type: 'xy';
categories: string[];
series: Series[];
axes?: Axis[];
horizontal?: boolean;
stacked?: boolean;
/** Horizontal bars: first category at the top (default) or at the bottom. */
reverse?: boolean;
totals?: boolean;
legend?: boolean;
labelWidth?: number;
grid?: boolean | 'dashed';
/** Title under the horizontal axis. */
xTitle?: string;
/** Angle of the category labels (vertical charts), for example -45. */
labelAngle?: number;
lines?: ReferenceLine[];
annotations?: Annotation[];
/** Drag on the chart to look closer, double click to come back (vertical charts). */
zoom?: boolean;
/** No axis, no legend, no margin: a sparkline. */
bare?: boolean;
}
export interface PieSpec extends Base {
type: 'pie';
data: { name: string; value: number; color?: string }[];
inner?: number;
outer?: number;
labels?: boolean;
/** Outside label of a slice. */ label?: (name: string, value: number, percent: number) => string;
/** Text in the hole of a donut. */ center?: string;
}
export interface RadarSpec extends Base {
type: 'radar';
indicators: { name: string; max?: number }[];
series: { name: string; values: number[]; color?: string }[];
}
export interface GaugeSpec extends Base {
type: 'gauge';
value: number;
max?: number;
color?: string;
/** Mark on the arc. */ target?: number;
name?: string;
unit?: string;
}
export interface ScatterPoint {
x: number;
y: number;
r?: number;
label: string;
color?: string;
id?: string;
/** Radius in pixels, instead of `r`. */ radius?: number;
group?: string;
[key: string]: unknown;
}
export interface ScatterSpec extends Base {
type: 'scatter';
data: ScatterPoint[];
color?: string;
xLabel?: string;
yLabel?: string;
/** Names written above the points. */
labels?: boolean;
legend?: boolean;
lines?: ReferenceLine[];
annotations?: Annotation[];
tooltip?: (point: ScatterPoint, format: (v: number) => string) => string[];
onPointClick?: (point: ScatterPoint) => void;
}
export interface Item {
name: string;
value: number;
color?: string;
label?: string;
id?: string;
}
interface Clickable {
onItemClick?: (id: string) => void;
}
export interface TreemapSpec extends Base, Clickable {
type: 'treemap';
data: Item[];
}
export interface PackSpec extends Base, Clickable {
type: 'pack';
data: Item[];
}
export interface FunnelSpec extends Base, Clickable {
type: 'funnel';
data: Item[];
/** Share of the first step (default) or of the previous one. */ rate?: 'first' | 'previous' | false;
}
/** Steps from a start to an end; `total: true` restarts from zero. */
export interface WaterfallSpec extends Base {
type: 'waterfall';
data: { name: string; value: number; total?: boolean; color?: string }[];
up?: string;
down?: string;
totalColor?: string;
}
export interface HeatmapSpec extends Base {
type: 'heatmap';
columns: string[];
rows: string[];
values: (number | null)[][];
color?: string;
/** Values written in the cells. */ labels?: boolean;
labelWidth?: number;
}
export interface TimelineBar {
row: string;
start: number;
end: number;
color?: string;
label?: string;
detail?: string;
}
export interface TimelineMark {
row: string;
at: number;
color?: string;
label?: string;
id?: string;
}
/** Dates are timestamps in milliseconds. */
export interface TimelineSpec extends Base, Clickable {
type: 'timeline';
rows: string[];
bars?: TimelineBar[];
marks?: TimelineMark[];
now?: number;
nowLabel?: string;
labelWidth?: number;
formatDate?: (t: number) => string;
}
export interface TreeNode {
name: string;
color?: string;
children?: TreeNode[];
}
/** Radial tree; a click on a node folds or unfolds it. */
export interface TreeSpec extends Base {
type: 'tree';
root: TreeNode;
/** Deepest level whose names are written. */ labelDepth?: number;
}
/** A type added with `registerChart`. */
export interface CustomSpec extends Base {
type: `custom:${string}`;
[key: string]: unknown;
}
export type BasicCharts =
| XYSpec
| PieSpec
| RadarSpec
| GaugeSpec
| ScatterSpec
| TreemapSpec
| PackSpec
| FunnelSpec
| WaterfallSpec
| HeatmapSpec
| TimelineSpec
| TreeSpec;
export type ChartSpec =
| BasicCharts
| FinanceCharts
| DistributionCharts
| ComparisonCharts
| CircularCharts
| FlowCharts
| DiagramCharts
| GridCharts
| MapCharts /* families */
| CustomSpec;
export interface AnimationOptions {
/** 2 is twice as fast. */
speed?: number;
/** Milliseconds for each element, instead of the timing of the chart. */
duration?: number;
/** Milliseconds before the first element. */
delay?: number;
/** `false`: everything moves together. */
stagger?: boolean;
/** Any CSS easing. */
easing?: string;
/** `fade` replaces movement by a fade. */
effect?: 'default' | 'fade';
/** When to play: at once, when first seen on screen, or by `play()`. */
start?: 'load' | 'visible' | 'manual';
}
export type ThemeInput = Partial | 'light' | 'dark' | 'auto';
export type ExportFormat = 'svg' | 'png' | 'csv';
export interface ExportOptions {
/** Written in the file only. */
title?: string;
subtitle?: string;
caption?: string;
background?: string;
padding?: number;
/** PNG only. */
scale?: number;
}
export interface ToolbarOptions {
formats?: readonly ExportFormat[];
label?: string;
labels?: Partial>;
icon?: string;
fileName?: string;
options?: ExportOptions;
}
export interface RenderOptions {
/** A named theme, or your own colours. Stylesheets can also set `--nervure-*`. */
theme?: ThemeInput;
locale?: string;
/** `false` draws at once. */
animation?: boolean | AnimationOptions;
/** Short form of `animation`. */
animate?: boolean;
/** The reader shows or hides a series in the legend. */
onToggle?: (name: string, visible: boolean) => void;
/** Export button. */
toolbar?: boolean | ToolbarOptions;
}
export interface ChartHandle {
readonly svg: SVGSVGElement;
/** Draws another spec, with its entrance animation. */
update(spec: ChartSpec, options?: RenderOptions): void;
/** Draws new data at once, without animation (live charts). */
refresh(spec: ChartSpec): void;
resize(): void;
/** Plays the entrance animation (again). */
play(): void;
/** Colour of a series or of an item, by name. Kept until `resetColors`. */
setColor(name: string, color: string): void;
setPalette(colors: string[]): void;
resetColors(): void;
/** Adds a note or a line (`xy` and `scatter`). Kept until `clearNotes`. */
addAnnotation(note: Annotation): void;
addLine(line: ReferenceLine): void;
clearNotes(): void;
/** Shows or hides a series, as the legend does. */
toggle(name: string, visible?: boolean): void;
/** Shows the categories from one index to another (`xy` with `zoom`). */
zoom(from: number, to: number): void;
resetZoom(): void;
destroy(): void;
/** Standalone SVG document. */
toSVG(options?: ExportOptions): string;
toPNG(options?: ExportOptions | number, background?: string): Promise;
toCSV(): string;
/** Saves a file on the reader's computer. */
download(format: ExportFormat, fileName?: string, options?: ExportOptions): Promise;
}
```