# LovelyChart documentation
> LovelyChart is a dependency-free JavaScript library of Telegram-style interactive charts for the web, written in TypeScript: line, area, bar, step, pie and donut charts drawn on canvas, with a tooltip, a legend, a draggable minimap, drill-down zooming, annotations, day and night skins and colours from CSS variables.
Key facts:
- Install with `npm install lovely-chart`. The package is one ES module with its TypeScript declarations and no dependencies; there is no CommonJS or UMD build.
- Import the class, the default export, and the stylesheet once: `import LovelyChart from 'lovely-chart'` and `import 'lovely-chart/LovelyChart.css'`. A chart needs the stylesheet.
- Build a chart with `new LovelyChart(element, { type, labels, datasets })`: `type` is `line`, `area`, `bar`, `step`, `pie` or `donut`; `labels` are UNIX timestamps in milliseconds, or strings; each dataset is `{ name, values }`, with `values[i]` at `labels[i]`.
- The instance has `update(newData, options?)`, `destroy()` and a few more methods to drive it.
- The chart fills the width of its element and builds again when the width of the window changes, not when only the element resizes.
- The `theme-dark` class on `` switches the chart to its night skin, or `colorScheme: 'system'` follows the system setting.
- The examples of these docs import `./demo-data.js` and fetch `../data/*.json`, which are helpers of the docs at https://lovelychart.io/examples/demo-data.js and https://lovelychart.io/data/, not part of the package.
---
# Introduction
LovelyChart is a small, dependency-free library of Telegram-style interactive charts for the web, minimalist and lovely out of the box. Give it an element and your data, and it draws a line, area, bar, step, pie or donut chart on canvas, with a tooltip, a legend, a draggable minimap and drill-down zooming built in.
```js
import LovelyChart from 'lovely-chart';
const data = await fetch('../data/bars.json').then((r) => r.json());
new LovelyChart(document.getElementById('chart'), {
...data,
title: 'Fruit sales',
// A click on a day opens its shares as a donut
zoomToShares: true,
zoomType: 'donut',
isUtc: true,
});
```
Try it out:
- Point at a day to read its values in the tooltip.
- Drag the window under the plot to show another period, or pull its edges to show a longer or shorter one.
- Click a fruit in the legend to hide or show it. Press and hold one to show it alone.
- Click a day to drill into its shares, then use **Zoom out** to go back. On a touch screen, tap the tooltip instead.
LovelyChart draws the statistics of [Telegram Web](https://web.telegram.org/a/) and the portfolio charts of [My Wallet](https://mywallet.io). It is an award winner of the [Telegram Chart Contest](https://contest.dev/chart-js).
## Why LovelyChart
- **Small and self-contained.** It has no dependencies: you get one ES module and one stylesheet. Importing it touches neither the DOM nor `window`, so it's safe to import in server-rendered apps.
- **Six chart types.** Line, area, bar, step, pie and donut. Areas and bars stack, and areas can show percentages. You can draw some datasets as lines, bars or steps over another chart type, put one dataset on a second Y axis, or shrink a chart to a sparkline. See [Chart types](https://lovelychart.io/guide/chart-types.md).
- **Built for exploring.** A minimap under the plot holds a window that the reader drags and resizes to pick a period. You can also let a mouse select a period by dragging across the plot. Range changes, legend toggles and zooms all animate smoothly.
- **Drill-down zoom.** A click on a label opens its shares as a pie or donut, or loads more detailed data of your own, such as the hours of a day. See [Zoom](https://lovelychart.io/guide/zoom.md).
- **Tooltip and legend.** The tooltip lists the values at a label, with a total for stacked charts, the change against a previous period and notes of your own. The legend buttons show and hide datasets.
- **Day and night skins.** The chart follows a `theme-dark` class on ``, or the system's colour scheme. Every colour option takes a CSS colour, a pair of colours with one for each skin, or a `var()` of your page. See [Theming](https://lovelychart.io/guide/theming.md).
- **Annotations.** Reference lines at fixed values, hatched ranges for forecasts and estimates, event lines for launches and outages, and a dashed line for a previous period. See [Annotations](https://lovelychart.io/guide/annotations.md).
- **Touch-friendly and fast.** Everything works by touch, and it's fast enough for low-end mobile devices.
- **Fits into your page.** CSS variables set the plot height, spacing and fonts. You can move the legend into an element of your own, react to the reader through callbacks, and place your own elements over the plot. See [Layout](https://lovelychart.io/guide/layout.md) and [Overlays](https://lovelychart.io/guide/overlays.md).
- **Accessible.** The plot is announced as an image with a summary of its data, the legend buttons work from the keyboard, and with `isKeyboardSelectable` the arrow keys step through the labels. See [Accessibility](https://lovelychart.io/guide/accessibility.md).
- **Typed.** TypeScript declarations ship in the package.
## What it's for, and what it isn't
LovelyChart is a good fit for:
- Time series on dashboards, admin panels and statistics pages: yearly, monthly, weekly, daily, hourly or five-minute data.
- Comparing a few series, or showing how a total splits into parts, over time.
- Categories with text labels, such as the days of the week.
- Pages that people use on phones, where charts have to work by touch.
Look elsewhere if you need:
- **Other kinds of chart.** It draws the six types above, so there are no scatter, bubble, radar, candlestick or heatmap charts, and no maps.
- **A numeric X axis.** The X axis is a sequence of labels, timestamps or text, each an equal step apart. There's no way to place a value between two labels, or at a distance set by its time.
- **Charts without a browser.** LovelyChart draws into a page's DOM and canvas, so it can't render a chart on a server, and it has no API to export one as an image.
## How it works
You create a chart with `new LovelyChart(element, params)`. It builds itself inside `element`, takes its full width, and stays interactive until you call `destroy()`. `params` is a plain object: the chart `type`, the `labels` along the X axis, the `datasets` with their values, and any options you need.
```js
import LovelyChart from 'lovely-chart';
import 'lovely-chart/LovelyChart.css';
const chart = new LovelyChart(document.getElementById('chart'), {
title: 'Online users',
type: 'line',
labels: [1735689600000, 1735776000000, 1735862400000],
datasets: [
{ name: 'Desktop', values: [1274, 1305, 1288] },
{ name: 'Mobile', values: [2861, 2914, 2950] },
],
});
// Later: new data, then cleanup
chart.update(nextParams);
chart.destroy();
```
The instance has a few more methods for driving the chart from your page, such as `selectLabel()`, `zoomOut()` and `setLoading()`. See the [API reference](https://lovelychart.io/guide/api.md).
## Where to go next
- [Installation](https://lovelychart.io/guide/installation.md): npm, a CDN, TypeScript and browser support.
- [Your first chart](https://lovelychart.io/guide/getting-started.md): a step-by-step walkthrough, from an empty element to a chart with a minimap.
- [Using with frameworks](https://lovelychart.io/guide/frameworks.md): React, Vue, Svelte, Angular and Web Components.
- [Data format](https://lovelychart.io/guide/data.md): labels, datasets, gaps and colours.
- [Chart types](https://lovelychart.io/guide/chart-types.md): every type, and which one to pick.
- [API reference](https://lovelychart.io/guide/api.md): every option and method, in full.
---
# Installation
LovelyChart ships as one ES module and one stylesheet. Install it from npm for an app with a bundler, or load both files from a CDN for a plain HTML page.
## Install from npm
Add the package with your package manager:
```bash
npm install lovely-chart
```
```bash
yarn add lovely-chart
```
```bash
pnpm add lovely-chart
```
## Import the module and the stylesheet
Import the `LovelyChart` class, the default export, and the stylesheet:
```js
import LovelyChart from 'lovely-chart';
import 'lovely-chart/LovelyChart.css';
const chart = new LovelyChart(document.getElementById('chart'), params);
```
The stylesheet lays out the header, the minimap, the legend and the tooltip, and holds the colours of the day and night skins as CSS variables. A chart needs it, so import it once for your whole app, for example in your entry file.
Besides the class, the module has three named exports for elements of your page that show the same series as a chart, such as a table beside it:
| Export | What it is |
| --- | --- |
| [`getDefaultColors(datasetCount)`](https://lovelychart.io/guide/api.md#getDefaultColors) | The colours a chart of that many datasets gives the datasets with no `color` |
| [`DEFAULT_COLORS`](https://lovelychart.io/guide/api.md#DEFAULT_COLORS) | The eight default colours, in order |
| [`DEFAULT_COMPARISON_COLOR`](https://lovelychart.io/guide/api.md#DEFAULT_COMPARISON_COLOR) | The colour of the `comparison` line when it sets none |
```js
import LovelyChart, { getDefaultColors } from 'lovely-chart';
```
### Import paths
The package's `exports` field makes three paths public:
| Path | File |
| --- | --- |
| `lovely-chart` | `dist/LovelyChart.js`, with its types in `dist/LovelyChart.d.ts` |
| `lovely-chart/LovelyChart.css` | `dist/LovelyChart.css` |
| `lovely-chart/package.json` | `package.json` |
> [!WARNING]
> Bundlers and Node refuse paths into `dist/` that `exports` doesn't list, such as `lovely-chart/dist/LovelyChart.css`. Import the stylesheet as `lovely-chart/LovelyChart.css`.
If your build doesn't handle CSS imports, copy `node_modules/lovely-chart/dist/LovelyChart.css` to where your site serves static files, and link it from your HTML with a ``.
### Modules and tree shaking
- **ES module only.** There's no CommonJS or UMD build. Load the package with `import`, or with a dynamic `import()` from CommonJS code.
- **Free of side effects.** `package.json` marks only the stylesheets as side effects, so `import 'lovely-chart/LovelyChart.css'` stays in your bundle, and the JavaScript you don't use can be dropped.
- **Minified.** The build is minified, 32 KB gzipped, so a page that loads it from a CDN downloads no more than a bundle would hold.
## Use it from a CDN
Without a bundler, load both files from [jsDelivr](https://www.jsdelivr.com/). The neatest way is an import map, which lets your scripts import `lovely-chart` by name, as they would with a bundler:
```html
```
For a single script, you can import the module from its URL instead:
```html
```
A module script runs once the document has been parsed, so the chart's element already exists when it runs.
> [!TIP]
> `lovely-chart@2` follows the latest 2.x release. In production, pin the exact version you've tested, such as `lovely-chart@2.3.0`, in both URLs.
## TypeScript
The package ships its TypeScript declarations, so there's nothing else to install. They resolve through the package's `exports`, with `moduleResolution` set to `node16` or `nodenext` too.
```ts
import LovelyChart, { type LovelyChartParams } from 'lovely-chart';
import 'lovely-chart/LovelyChart.css';
const params: LovelyChartParams = {
title: 'Orders',
type: 'line',
labels: [Date.UTC(2026, 10, 16), Date.UTC(2026, 10, 17), Date.UTC(2026, 10, 18)],
datasets: [{ name: 'Orders', values: [412, 438, null] }],
isUtc: true,
};
const chart: LovelyChart = new LovelyChart(document.getElementById('chart')!, params);
```
The module exports these types:
| Type | Describes |
| --- | --- |
| `LovelyChartParams` | The params of the constructor and of `update()`, and the data that `onZoom` resolves to |
| `LovelyChartDatasetParams` | One entry of `datasets` |
| `LovelyChartUpdateOptions` | The second argument of `update()` |
| `LovelyChartInstance` | The `update()` and `destroy()` methods of a chart, as a structural type for test stubs |
| `ChartType` | The chart types: `'line'`, `'bar'`, `'step'`, `'area'`, `'pie'` and `'donut'` |
| `LabelType` | The values of `labelType` |
| `ThemedColor` | A colour option: a CSS colour, or `{ light, dark }` |
| `DateLocale` | The localised date strings of `dateLocale` |
| `SecondaryYAxisConfig` | The `secondaryYAxis` scale |
| `ReferenceLine` | One entry of `referenceLines` |
| `HatchedRange` | One entry of `hatchedRanges` |
| `EventLine` | One entry of `eventLines` |
| `Comparison` | The previous period of `comparison` |
| `TooltipContent` | What `onTooltipChange` reports |
| `TooltipNotes` | What `resolveTooltipNotes` returns |
`LovelyChartInstance` lets a test hand your code a stand-in for a chart:
```ts
import type { LovelyChartInstance } from 'lovely-chart';
const chart: LovelyChartInstance = {
update() {},
destroy() {},
};
```
See [Types](https://lovelychart.io/guide/api.md#types) in the API reference for their full shapes.
## Browser support
LovelyChart runs in current browsers on desktop and mobile, by mouse, touch and keyboard.
- **Modern JavaScript.** The bundle targets `esnext`: it keeps the syntax of its source as it is, including native `#private` class members. A browser that lacks them can't load the module; Safari 14 is one. To support such a browser, have your bundler transpile `lovely-chart` along with your own code.
- **The project's target.** The repository's `.browserslistrc` reads `> 0.5%, not ie 11, not edge 17`. Internet Explorer isn't supported.
- **Server-side rendering.** Importing the package touches neither the DOM nor `window`, so a server can import it. Create charts only in the browser: see [Using with frameworks](https://lovelychart.io/guide/frameworks.md#server-side-rendering).
## Upgrading from 1.x
Version 2.0 changed how you create a chart. The main changes:
- `LovelyChart.create(element, data)` is gone. The class is the default export, and you create a chart with `new`:
```js
// 1.x
import * as LovelyChart from 'lovely-chart';
const chart = LovelyChart.create(element, data);
// 2.x
import LovelyChart from 'lovely-chart';
const chart = new LovelyChart(element, data);
```
- The `isDonut` parameter is gone: a donut is a type of its own, `type: 'donut'`.
- Pie and donut charts no longer need `isStacked` or `isPercentage`, and `isPercentage` no longer makes them zoomable.
- The internal class `lovely-chart--container-type-pie` is now `lovely-chart--container-type-circle`, so update any styles that target it.
The package's `CHANGELOG.md` lists every change since.
---
# Your first chart
This page takes you from an empty element to an interactive chart with a minimap, then shows you how to give it new data and how to remove it. Each step builds on the one before, and every example runs right here on the page.
## Before you start
[Install the package](https://lovelychart.io/guide/installation.md), then add an element for the chart to your page:
```html
```
Import the class and the stylesheet in your script:
```js
import LovelyChart from 'lovely-chart';
import 'lovely-chart/LovelyChart.css';
```
The chart fills the width of its element, so a block element such as a `
` works best. Its height comes from its content: the header, the plot, which is 320px high by default, and the minimap and legend when it has them.
> [!NOTE]
> The examples import made-up data from `./demo-data.js`, a helper of these docs. `days(count)` returns `count` daily timestamps at UTC midnight, and `series(count, options)` returns `count` values of a random walk. The same call gives the same numbers on every visit. In your app, the labels and values come from your own data.
## Draw a line
A chart needs three things: a `type`, the `labels` along the X axis, and the `datasets` to draw, each with a `name` and one value per label.
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
new LovelyChart(document.getElementById('chart'), {
type: 'line',
labels: days(30),
datasets: [
{ name: 'Visitors', values: series(30, { start: 3300, seasonality: 0.2, seed: 1 }) },
],
isUtc: true,
});
```
- `labels` are UNIX timestamps in milliseconds, one per day here. They can be text too: see [Data format](https://lovelychart.io/guide/data.md#labels).
- `isUtc: true` reads the dates in UTC, as `days()` makes them, so readers in every time zone see the same days.
Without any more options, you already get:
- A header with the dates on screen.
- A Y axis that fits the values, and dates along the X axis.
- A tooltip with the value at the label under the pointer, or under your finger on a touch screen.
- The day or night skin of the page.
A chart of a single dataset has no legend, as there's nothing to switch between.
## Add a title and a second dataset
Add a `title` to the header, and a second dataset. Each dataset can take a `color`; the ones without take a colour from the [default palette](https://lovelychart.io/guide/data.md#default-colours).
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
new LovelyChart(document.getElementById('chart'), {
title: 'Visitors',
type: 'line',
labels: days(30),
datasets: [
{ name: 'Desktop', color: '#3497ED', values: series(30, { start: 1200, seasonality: 0.2, seed: 1 }) },
{ name: 'Mobile', color: '#5FB641', values: series(30, { start: 2100, seasonality: 0.2, seed: 2 }) },
],
isUtc: true,
});
```
With two datasets, the chart adds a legend. Click a button to hide or show its dataset, and the Y axis animates to fit the datasets on screen. The legend never lets the reader hide every dataset. The tooltip now lists both datasets, the larger value first.
## Add a minimap
For a longer period, add `withMinimap: true`. The minimap draws every label under the plot, with a window over the ones the plot shows. The reader drags the window to move through the period and pulls its edges to show more or fewer labels.
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
new LovelyChart(document.getElementById('chart'), {
title: 'Visitors',
type: 'line',
labels: days(180),
datasets: [
{ name: 'Desktop', color: '#3497ED', values: series(180, { start: 1200, seasonality: 0.2, seed: 1 }) },
{ name: 'Mobile', color: '#5FB641', values: series(180, { start: 2100, seasonality: 0.2, seed: 2 }) },
],
withMinimap: true,
// Open on the last 30 days: inclusive label indexes
minimapRange: { from: 150, to: 179 },
isUtc: true,
});
```
Without `minimapRange`, the window opens on the last 20% of the labels. Besides label indexes, it takes fractions of the whole period, such as `[0.5, 1]` for the second half, or `'full'` for all of it. See [`minimapRange`](https://lovelychart.io/guide/api.md#minimapRange) for every rule, and [Minimap](https://lovelychart.io/guide/minimap.md) for more.
## Give it new data
Call [`update()`](https://lovelychart.io/guide/api.md#update) with a new params object, of the same shape as the one you created the chart with. The chart rebuilds itself from it, in the same element. With the [`isAnimated`](https://lovelychart.io/guide/api.md#isAnimated) option, the old chart cross-fades into the new one.
```html
```
A few things to know about `update()`:
- **Pass a new object.** The chart keeps a reference to the params you give it and builds from them again on a window resize, so a change you make to that object later shows up at an unexpected moment. Build a new object for new data, as `getParams()` does here. See [Data format](https://lovelychart.io/guide/data.md#passing-new-data).
- **It resets the view.** The zoom, the window, the datasets hidden in the legend and the selected label start afresh, unless you keep them with the update options [`shouldKeepFilter`](https://lovelychart.io/guide/api.md#shouldKeepFilter), [`shouldKeepZoom`](https://lovelychart.io/guide/api.md#shouldKeepZoom) and [`shouldKeepSelection`](https://lovelychart.io/guide/api.md#shouldKeepSelection).
- **Motion is optional.** `isAnimated` is ignored while the reader's system asks for reduced motion, and the data swaps at once.
[Updating](https://lovelychart.io/guide/updating.md) goes through live data, polling and keeping the reader's view.
## Remove the chart
When the chart's element leaves the page, call [`destroy()`](https://lovelychart.io/guide/api.md#destroy). It removes everything the chart added to the element, detaches its listeners from the window and the document, and cancels its pending animation frames and timers. After that, the instance does nothing, and the element is free for a new chart.
```html
```
`destroy()` is safe to call more than once. In a framework, call it from the cleanup hook of the component that created the chart: see [Using with frameworks](https://lovelychart.io/guide/frameworks.md).
## Next steps
- [Data format](https://lovelychart.io/guide/data.md): text labels, gaps, dashed lines and colours.
- [Chart types](https://lovelychart.io/guide/chart-types.md): areas, bars, steps, pies and donuts, and how to mix them.
- [Tooltip](https://lovelychart.io/guide/tooltip.md), [Legend](https://lovelychart.io/guide/legend.md) and [Zoom](https://lovelychart.io/guide/zoom.md): what the reader can do with a chart, and how to shape it.
- [Theming](https://lovelychart.io/guide/theming.md): colours and the day and night skins.
---
# Using with frameworks
LovelyChart works with any framework, or none: all it needs is an element. A wrapper component creates the chart when it mounts, hands it new data with `update()`, and destroys it when it unmounts.
## The lifecycle
Every wrapper on this page follows the same three steps:
| When | Call | Why |
| --- | --- | --- |
| The component mounts | `new LovelyChart(element, params)` | Builds the chart inside the component's element |
| New data arrives | `chart.update(params)` | Rebuilds the chart from the new params, in the same element |
| The component unmounts | `chart.destroy()` | Removes the chart's DOM, detaches its window and document listeners, and cancels its animation frames and timers |
A few rules keep the wrappers simple and leak-free:
- **Give the chart an element of its own.** Render an empty element and let the chart fill it; don't have the framework render children into it. The chart adds its own DOM to the element and sets the `--lovely-chart-plot-area-*` CSS variables on its style.
- **Create the chart once its element is in the document.** The chart measures the width of its element as it builds. An element that is hidden at that moment, as in an inactive tab, has no width to measure, so create the chart when it's shown.
- **Pass a new object for new data.** The chart keeps a reference to the params you give it and builds from them again on a window resize. Frameworks that favour immutable data fit this naturally: see [Data format](https://lovelychart.io/guide/data.md#passing-new-data).
- **Keep the instance out of reactive state.** The chart keeps its state in native `#private` class fields, which a JavaScript `Proxy` can't reach: calling a method of the chart through a reactive proxy, such as Vue's `ref()`, throws a `TypeError`. Hold the instance in a plain variable, or in your framework's raw or shallow container.
- **Always destroy.** `destroy()` is idempotent, so a cleanup that runs twice does no harm.
`update()` resets the zoom, the window, the datasets hidden in the legend and the selected label. For live data, keep the reader's view with the update options:
```js
chart.update(params, { shouldKeepFilter: true, shouldKeepZoom: true, shouldKeepSelection: true });
```
See [Updating](https://lovelychart.io/guide/updating.md) for what each option keeps.
## React
Create the chart in an effect, and return `destroy()` as its cleanup. A second effect hands the chart new data:
```jsx
import { useEffect, useRef } from 'react';
import LovelyChart from 'lovely-chart';
import 'lovely-chart/LovelyChart.css';
export function Chart({ params }) {
const elementRef = useRef(null);
const chartRef = useRef(null);
// The params the chart on screen was built from
const builtParamsRef = useRef(params);
// Create on mount, destroy on unmount
useEffect(() => {
const chart = new LovelyChart(elementRef.current, builtParamsRef.current);
chartRef.current = chart;
return () => {
chart.destroy();
chartRef.current = null;
};
}, []);
// Rebuild from new params
useEffect(() => {
if (chartRef.current && params !== builtParamsRef.current) {
builtParamsRef.current = params;
chartRef.current.update(params);
}
}, [params]);
return ;
}
```
The check against `builtParamsRef` skips an `update()` right after the chart is created from the same params, which would rebuild it for nothing.
### Strict Mode
In development, Strict Mode mounts each component twice: it runs the effects, their cleanups, then the effects again. With the component above, that creates a chart, destroys it and creates a fresh one in the same element. `destroy()` removes everything the first chart added, so nothing is left over. If you see two charts in one element, an effect is missing its cleanup.
### Stable params
`update()` rebuilds the chart and resets the reader's view, so call it only when the data really changes. Build the params with `useMemo`, keyed by the data they come from, rather than as a new object literal on every render:
```jsx
import { useMemo } from 'react';
function OrdersChart({ rows }) {
const params = useMemo(() => ({
title: 'Orders',
type: 'bar',
labels: rows.map((row) => row.date),
datasets: [{ name: 'Orders', values: rows.map((row) => row.orders) }],
}), [rows]);
return ;
}
```
This matters most with callbacks in the params. `update()` reports the end of a selection to `onSelectedIndexChange`, so a callback that sets state, with params rebuilt on every render, would update the chart on every report and lose the selection each time.
In TypeScript, type the props with `LovelyChartParams`, and the refs as `useRef(null)` and `useRef(null)`.
> [!NOTE]
> In the Next.js App Router, a component that uses effects is a Client Component: start its file with `'use client'`. See [Server-side rendering](#server-side-rendering).
## Vue 3
Create the chart in `onMounted`, update it from a `watch` on the params, and destroy it in `onBeforeUnmount`:
```vue
```
- `toRaw()` hands the chart the plain object behind a reactive one, so it doesn't read every value through Vue's proxies.
- The `watch` fires when the parent passes a new params object, not when it changes the one it passed. Replace the params rather than mutating them; `shallowRef()` in the parent suits data that is replaced as a whole.
- If you'd rather keep the chart in a ref, use `shallowRef()` or wrap the instance in `markRaw()`.
## Svelte
An action is the most compact wrapper: Svelte calls it with the element once it's in the document, calls its `update` when the parameter changes, and its `destroy` when the element goes.
```svelte
```
The action is the same in Svelte 4, where the component takes `export let params;` in place of `$props()`.
In Svelte 5, keep the params in `$state.raw()` and replace them as a whole for new data: the chart gets a plain object, and a reassignment updates it.
### With onMount
If you'd rather have the instance in the component, for instance to call `chart.selectLabel()` from a button, create it in `onMount` and update it from an effect:
```svelte
```
## Angular
Create the chart in `ngAfterViewInit`, once the view holds its element, update it in `ngOnChanges`, and destroy it in `ngOnDestroy`:
```ts
import {
AfterViewInit, Component, ElementRef, inject, Input, NgZone, OnChanges, OnDestroy, ViewChild,
} from '@angular/core';
import LovelyChart, { type LovelyChartParams } from 'lovely-chart';
@Component({
selector: 'app-lovely-chart',
standalone: true,
template: '',
})
export class LovelyChartComponent implements AfterViewInit, OnChanges, OnDestroy {
@Input({ required: true }) params!: LovelyChartParams;
@ViewChild('chart') private element!: ElementRef;
private readonly zone = inject(NgZone);
private chart?: LovelyChart;
ngAfterViewInit() {
// The chart's animation frames and listeners need no change detection
this.zone.runOutsideAngular(() => {
this.chart = new LovelyChart(this.element.nativeElement, this.params);
});
}
ngOnChanges() {
// No chart yet on the first change: ngAfterViewInit creates it
this.zone.runOutsideAngular(() => this.chart?.update(this.params));
}
ngOnDestroy() {
this.chart?.destroy();
}
}
```
- **Run the chart outside the zone.** The chart draws on animation frames and listens to pointer moves over the document. Created inside Angular's zone, each of those would trigger change detection. Callbacks in the params then run outside the zone too: wrap the state changes they make in `this.zone.run(() => …)`. A zoneless app needs neither.
- **Add the stylesheet globally.** Component styles are scoped to the component's own template, and the chart builds its DOM itself, so they don't reach it. Add `node_modules/lovely-chart/dist/LovelyChart.css` to the `styles` array of your project's build options in `angular.json`, beside your own global stylesheet.
- **Pass new objects.** `ngOnChanges` runs when the parent binds a new params object, not when it changes the one it bound.
## Web Component
A custom element can wrap the chart for any page or framework: it creates the chart when it's added to the document, updates it when its `params` property is set, and destroys it when it's removed.
```js
import LovelyChart from 'lovely-chart';
import 'lovely-chart/LovelyChart.css';
class LovelyChartView extends HTMLElement {
#chart;
#params;
get params() {
return this.#params;
}
set params(params) {
this.#params = params;
if (this.#chart) {
this.#chart.update(params);
} else if (this.isConnected) {
this.#chart = new LovelyChart(this, params);
}
}
connectedCallback() {
if (this.#params && !this.#chart) {
this.#chart = new LovelyChart(this, this.#params);
}
}
disconnectedCallback() {
this.#chart?.destroy();
this.#chart = undefined;
}
}
customElements.define('lovely-chart-view', LovelyChartView);
```
A custom element is inline by default, so make it a block:
```css
lovely-chart-view {
display: block;
}
```
Then set its `params` from a script:
```html
```
- **Keep it in the light DOM.** The element holds the chart itself, with no shadow root, so the library's stylesheet reaches it from the document. With the default `colorScheme`, the night skin hangs off a `theme-dark` class on ``, which a stylesheet inside a shadow root can't see.
- **Moving the element rebuilds the chart.** Moving it in the document disconnects and reconnects it, which destroys the chart and creates a new one, with a fresh view.
## Server-side rendering
Importing `lovely-chart` touches neither the DOM nor `window`, so server-rendered code can import it. Creating a chart needs a browser. React's `useEffect`, Vue's `onMounted`, Svelte's actions and `onMount`, and a custom element's `connectedCallback` only run there, so the wrappers above need no change: on the server, the component renders its empty element, and the chart builds itself in it once the page runs in the browser.
Angular is the exception: with server-side rendering, it runs `ngAfterViewInit` on the server too. Create the chart only in the browser there, for example behind a check of `isPlatformBrowser()`:
```ts
import { isPlatformBrowser } from '@angular/common';
import { inject, PLATFORM_ID } from '@angular/core';
// In the component
private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
ngAfterViewInit() {
if (!this.isBrowser) return;
this.zone.runOutsideAngular(() => {
this.chart = new LovelyChart(this.element.nativeElement, this.params);
});
}
```
The stylesheet import is plain CSS, so it works in server builds as long as your framework accepts CSS from packages. Import it once, where your framework takes global styles.
---
# Data format
Every chart takes one plain object: a `type`, the `labels` along the X axis, and the `datasets` to draw, each with a value per label. This page covers those three, and how the chart treats the object you hand it.
## The shape of the data
```js
const params = {
title: 'Orders', // optional headline
type: 'line', // 'line', 'area', 'bar', 'step', 'pie' or 'donut'
labels: [1793491200000, 1793577600000, 1793664000000], // 1–3 Nov 2026, one per point or column
datasets: [
{ name: 'iOS', values: [412, 438, 451] }, // one value per label
{ name: 'Android', values: [389, 402, 417] },
],
// ...any other options
};
new LovelyChart(element, params);
```
`labels` and each dataset's `values` line up by index: `values[i]` is the value at `labels[i]`. Every other option has a sensible default; see the [options reference](https://lovelychart.io/guide/api.md#chart-options) for all of them.
## Labels
[`labels`](https://lovelychart.io/guide/api.md#labels) are either UNIX timestamps in milliseconds or text strings.
The chart places each label an equal step along the X axis, whatever the time between two timestamps. So give every period its own label, and mark a period with no data with a `null` value rather than leaving its label out: see [Gaps](#gaps).
### Timestamps
Timestamps give you date labels on the X axis, dates in the tooltip title, and a caption of the dates on screen in the header.
```js
// Midnight UTC of 16 November 2026
const label = Date.UTC(2026, 10, 16);
// The same instant from an ISO date
const sameLabel = new Date('2026-11-16').getTime();
```
> [!TIP]
> A day label shows the date in the reader's time zone, so a reader west of UTC sees a timestamp at UTC midnight as the day before. For daily data at UTC midnight, set [`isUtc: true`](https://lovelychart.io/guide/api.md#isUtc) to read every date in UTC. See [Time zones](https://lovelychart.io/guide/dates.md#time-zones).
### Label type
The chart works out how to name the labels from the step between the first two timestamps. You can set it yourself with [`labelType`](https://lovelychart.io/guide/api.md#labelType).
| Step between the first two labels | Inferred `labelType` | X-axis label |
| --- | --- | --- |
| 365 days or more | `year` | `2026` |
| 28 days or more | `month` | `January` |
| 7 days or more | `week` | `Week 47` |
| A day or more | `day` | `16 Nov` |
| An hour or more | `hour` | `14:00` |
| Less than an hour | `5min` | `14:05` |
Text labels always take `text`, and a single timestamp takes `day`. `dayHour`, which labels each point with its date and hour, is never inferred: set it when you need it.
Here, labels a month apart read as month names:
```js
import LovelyChart from 'lovely-chart';
import { months, series } from './demo-data.js';
new LovelyChart(document.getElementById('chart'), {
title: 'Monthly revenue',
type: 'bar',
labels: months(12),
datasets: [
{ name: 'Revenue', values: series(12, { start: 48000, trend: 0.02, seed: 5 }) },
],
valuePrefix: '$',
});
```
To format the labels of timestamps differently, as dates for weekly data, see [Axis label formats](https://lovelychart.io/guide/dates.md#axis-label-formats).
### Text labels
Strings make a category axis, with each string as its label and the tooltip title:
```js
import LovelyChart from 'lovely-chart';
new LovelyChart(document.getElementById('chart'), {
title: 'Orders by weekday',
type: 'bar',
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
datasets: [
{ name: 'Orders', values: [412, 438, 451, 469, 520, 610, 574] },
],
});
```
A chart of text labels has no dates to show, so its header holds the `title` alone. Without a `title`, the header folds away and the plot starts at the top of the chart.
## Datasets
Each entry of [`datasets`](https://lovelychart.io/guide/api.md#datasets) is one series:
| Field | What it does |
| --- | --- |
| [`name`](https://lovelychart.io/guide/api.md#datasets-name) | Names the dataset in the legend and the tooltip. Required. |
| [`values`](https://lovelychart.io/guide/api.md#datasets-values) | One number per label, or `null` for a gap. Required. |
| [`color`](https://lovelychart.io/guide/api.md#datasets-color) | Any CSS colour, `{ light, dark }` for one per skin, or a `var()` of your page. Defaults to the [default colours](#default-colours). |
| [`isInitiallyHidden`](https://lovelychart.io/guide/api.md#datasets-isInitiallyHidden) | Starts the dataset hidden, its legend button unchecked. |
| [`isDashed`](https://lovelychart.io/guide/api.md#datasets-isDashed) | Draws a line or step dataset in dashes. |
| [`isDotted`](https://lovelychart.io/guide/api.md#datasets-isDotted) | Draws a line or step dataset in dots. |
| [`type`](https://lovelychart.io/guide/api.md#datasets-type) | Draws the dataset as a `line`, `bar` or `step` over a chart of another type. |
Colours have a page of their own: see [Theming](https://lovelychart.io/guide/theming.md).
### Gaps
A `null` value leaves a gap, for a period with no data. A line breaks at the gap, and the tooltip leaves out a dataset with no value at the label.
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
const web = series(30, { start: 240, seasonality: 0.2, seed: 8 });
// Tracking was down for three days
web.fill(null, 12, 15);
new LovelyChart(document.getElementById('chart'), {
title: 'Sign-ups',
type: 'line',
labels: days(30),
datasets: [
{ name: 'Web', values: web },
{ name: 'App', values: series(30, { start: 180, seasonality: 0.2, seed: 9 }) },
],
isUtc: true,
});
```
Other types treat gaps in kind: a bar chart draws no bar at a gap, and an area splits at a gap and fills each run on its own. A line run of one or two values between gaps draws as dots, and so does a lone value of an area.
> [!NOTE]
> The tooltip leaves out a dataset whose value at the label is `0` too. [`onTooltipChange`](https://lovelychart.io/guide/api.md#onTooltipChange) still reports it, with `0`, and a gap as `null`.
### Hidden, dashed and dotted datasets
`isInitiallyHidden` starts a dataset hidden, for a series the reader can bring in from the legend. `isDashed` and `isDotted` tell lines of one colour apart, as an actual value from a target. Both apply to `line` and `step` datasets only; other types ignore them.
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
const labels = days(60);
new LovelyChart(document.getElementById('chart'), {
title: 'Revenue',
type: 'line',
labels,
datasets: [
{ name: 'Actual', color: '#3497ED', values: series(60, { start: 8200, trend: 0.004, volatility: 0.04, seed: 18 }) },
{ name: 'Target', color: '#3497ED', isDashed: true, values: labels.map((_, i) => 8000 + i * 40) },
{
name: 'Last year',
color: '#3497ED',
isDotted: true,
isInitiallyHidden: true,
values: series(60, { start: 7100, trend: 0.003, volatility: 0.04, seed: 44 }),
},
],
valuePrefix: '$',
isUtc: true,
});
```
The legend buttons and the tooltip swatches of dashed and dotted datasets take a dashed or dotted outline too. A single dataset normally has no legend, but one that starts hidden keeps it, as the legend is the only way to show it.
### Default colours
A dataset without a `color` takes one of eight default colours:
`#3497ED`, `#2373DB`, `#9ED448`, `#5FB641`, `#F5BD25`, `#F79E39`, `#E65850` and `#5D5CDC`.
A chart of fewer than eight datasets takes a subset of them whose hues stand apart: `#3497ED` and `#9ED448` for two, then `#F79E39` for a third, and so on. A chart of more than eight starts over from the first. The colours go in order to the datasets without a `color`, so when none has one, the dataset at index `i` takes the colour at index `i`.
To show the same colours elsewhere on your page, as in a table beside the chart, ask [`getDefaultColors()`](https://lovelychart.io/guide/api.md#getDefaultColors) for them:
```js
import { getDefaultColors } from 'lovely-chart';
const regions = ['Europe', 'Americas', 'Asia'];
const colors = getDefaultColors(regions.length);
const regionColors = Object.fromEntries(regions.map((name, i) => [name, colors[i]]));
// { Europe: '#3497ED', Americas: '#9ED448', Asia: '#F79E39' }
```
[`DEFAULT_COLORS`](https://lovelychart.io/guide/api.md#DEFAULT_COLORS) holds all eight, in order, as a frozen array.
### Datasets of another type
A dataset's `type` draws it as a `line`, `bar` or `step` over a chart of another type, such as an average line over daily bars. Such a dataset draws its own values, outside the stack and the tooltip's total. See [Mixing types](https://lovelychart.io/guide/chart-types.md#mixing-types).
## Pie and donut of totals
A pie or donut of a total per dataset takes a single text label, as `labels: ['Total']`, and each dataset's `values` holds its total:
```js
import LovelyChart from 'lovely-chart';
new LovelyChart(document.getElementById('chart'), {
title: 'Traffic sources',
type: 'pie',
labels: ['Total'],
datasets: [
{ name: 'Search', values: [48210] },
{ name: 'Direct', values: [21840] },
{ name: 'Social', values: [12370] },
{ name: 'Email', values: [6950] },
{ name: 'Referral', values: [4120] },
],
});
```
As with any text label, the header shows no dates. A pie or donut can also take many labels, and then sums the values of the period on screen: see [Chart types](https://lovelychart.io/guide/chart-types.md#pie).
## Passing new data
The chart keeps a reference to the params object you pass to the constructor or to [`update()`](https://lovelychart.io/guide/api.md#update). It builds from that object again whenever it rebuilds itself, as on a window resize or an orientation change. So a change you make to the object later doesn't show when you make it, but at the next rebuild.
Treat the object as the chart's from then on, and build a new one for new data:
```js
const chart = new LovelyChart(element, params);
// Don't: the chart holds this object, so the new title shows only at its next rebuild
params.title = 'Orders, net';
// Do: pass a new object
chart.update({ ...params, title: 'Orders, net' });
// The same for new values: new arrays in a new object
chart.update({
...params,
labels: [...params.labels, nextDay],
datasets: params.datasets.map((dataset, i) => ({
...dataset,
values: [...dataset.values, nextValues[i]],
})),
});
```
`update()` resets the zoom, the window, the datasets hidden in the legend and the selection, unless its options keep them. See [Updating](https://lovelychart.io/guide/updating.md).
---
# Chart types
LovelyChart draws six types of chart: line, area, bar, step, pie and donut. You pick one with [`type`](https://lovelychart.io/guide/api.md#type), then shape it with stacking, percentages, datasets of other types, a second Y axis or a sparkline.
> [!NOTE]
> The daily data in these examples sits at UTC midnight, so the examples set [`isUtc: true`](https://lovelychart.io/guide/api.md#isUtc) to show the same days to readers in every time zone. See [Time zones](https://lovelychart.io/guide/dates.md#time-zones).
## Which type when
| Type | Use it to show | Params |
| --- | --- | --- |
| Line | Trends over time, and how a few series compare | `type: 'line'` |
| Stacked area | A total and the parts it's made of, over time | `type: 'area'`, `isStacked: true` |
| Percentage area | How the shares of a whole change over time | `type: 'area'`, `isPercentage: true` |
| Bar | An amount per period, such as orders per day | `type: 'bar'` |
| Stacked bar | An amount per period and its parts, negative ones included | `type: 'bar'`, `isStacked: true` |
| Step | Values that hold until they change: prices, plans, limits | `type: 'step'` |
| Pie | The parts of a whole, a handful of them, at a glance | `type: 'pie'` |
| Donut | The same as a pie, as a ring | `type: 'donut'` |
| Bars and a line | Amounts with an average or a target over them | `datasets[*].type` |
| Two Y axes | Two measures of different scales, such as a count and a rate | `hasSecondYAxis: true` |
| Sparkline | A small trend in a table row or a card | `isSparkline: true` |
## Line
A line chart joins the values of each dataset with a line. It's the default choice for trends over time.
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
new LovelyChart(document.getElementById('chart'), {
title: 'Response time',
type: 'line',
labels: days(60),
datasets: [
{ name: 'Median', values: series(60, { start: 120, volatility: 0.05, seed: 3 }) },
{ name: '95th percentile', values: series(60, { start: 340, volatility: 0.08, seed: 4 }) },
],
valueSuffix: ' ms',
areLinesSmooth: true,
isUtc: true,
});
```
- [`areLinesSmooth`](https://lovelychart.io/guide/api.md#areLinesSmooth) draws each line as a curve through its values that never overshoots a value. Lines are straight segments by default.
- The Y range starts at 0, unless the values go below 0 or their lowest is more than three quarters of their highest; then it fits the values. See [The Y axis range](https://lovelychart.io/guide/axes.md#the-y-axis-range).
- Lines can be dashed or dotted, and break at `null` values: see [Data format](https://lovelychart.io/guide/data.md#datasets).
## Area
An area chart fills the space under each line. Areas are at their best stacked, as parts of a total.
### Stacked areas
[`isStacked`](https://lovelychart.io/guide/api.md#isStacked) piles each dataset on top of the ones before it, so the top edge traces the total:
```js
import LovelyChart from 'lovely-chart';
// A year of daily sales of six fruits
const data = await fetch('../data/areas-absolute.json').then((r) => r.json());
new LovelyChart(document.getElementById('chart'), {
...data,
title: 'Fruit sales',
type: 'area',
isStacked: true,
withMinimap: true,
isUtc: true,
});
```
The tooltip of a stacked chart adds a Total row under the datasets. Hide a fruit in the legend, and the stack closes up around the gap.
### Percentage areas
[`isPercentage`](https://lovelychart.io/guide/api.md#isPercentage) shows each label's values as shares of their total, stacked to 100%. It stacks the datasets by itself, with no need for `isStacked`.
```js
import LovelyChart from 'lovely-chart';
const data = await fetch('../data/areas.json').then((r) => r.json());
new LovelyChart(document.getElementById('chart'), {
...data,
title: 'Share of fruit sales',
type: 'area',
isPercentage: true,
withMinimap: true,
isUtc: true,
});
```
- The Y axis runs from 0 to 100%, and the tooltip prints each dataset's share beside its value. [`percentPrecision`](https://lovelychart.io/guide/api.md#percentPrecision) sets the digits of the share after the point, `0` by default.
- A percentage chart zooms by itself: click a day to open its shares as a pie, then **Zoom out** to go back. [`zoomType: 'donut'`](https://lovelychart.io/guide/api.md#zoomType) makes it a donut, and [`noZoom: true`](https://lovelychart.io/guide/api.md#noZoom) turns the zoom off. A stacked chart of absolute values can do the same with [`zoomToShares`](https://lovelychart.io/guide/api.md#zoomToShares). See [Zoom](https://lovelychart.io/guide/zoom.md).
### Fill opacity and outline
Without `isStacked`, each area fills from its line down to zero, over the areas before it. [`areaOpacity`](https://lovelychart.io/guide/api.md#areaOpacity), from 0 to 1, makes the fills translucent while the outline and the dots keep their full opacity. [`areaBorderColor`](https://lovelychart.io/guide/api.md#areaBorderColor) draws a 1px outline around each area, in one colour for every area or one per skin.
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
new LovelyChart(document.getElementById('chart'), {
title: 'Active users',
type: 'area',
labels: days(90),
datasets: [{
name: 'Active users',
color: '#3497ED',
values: series(90, { start: 12000, trend: 0.004, seasonality: 0.1, seed: 31 }),
}],
areaOpacity: 0.25,
areaBorderColor: '#3497ED',
isUtc: true,
});
```
On a stack, `areaBorderColor` draws a boundary that two areas share only once.
## Bar
A bar chart gives every label a column and fills it from zero to the value. It suits amounts that belong to a period, such as orders per day or revenue per month.
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
new LovelyChart(document.getElementById('chart'), {
title: 'Orders by platform',
type: 'bar',
isStacked: true,
labels: days(30),
datasets: [
{ name: 'iOS', values: series(30, { start: 420, seasonality: 0.2, seed: 21 }) },
{ name: 'Android', values: series(30, { start: 380, seasonality: 0.2, seed: 22 }) },
{ name: 'Web', values: series(30, { start: 160, seasonality: 0.2, seed: 23 }) },
],
isUtc: true,
});
```
- Hovering a column dims the columns around it, and the tooltip lists its values with a Total row.
- Give a bar chart of several datasets `isStacked: true`. Without it, every dataset fills the same full-width column from zero, so the bars of one label draw over each other.
- A stack takes negative values too: they stack down from zero, under the positive ones, as for revenue, refunds and adjustments.
- `isPercentage: true` makes every column a 100% stack of shares.
## Step
A step chart holds each value flat across its label's column and jumps at the boundary to the next one. Reach for it for values that stay put until they change: prices, plans, rate limits or quotas.
```js
import LovelyChart from 'lovely-chart';
import { days } from './demo-data.js';
const labels = days(30);
// The price set on the latest day of a change, for each day
const prices = (changes) => labels.map((_, day) => changes.findLast(([from]) => from <= day)[1]);
new LovelyChart(document.getElementById('chart'), {
title: 'Plan prices',
type: 'step',
labels,
datasets: [
{ name: 'Basic', values: prices([[0, 9], [12, 12]]) },
{ name: 'Pro', values: prices([[0, 29], [8, 24], [20, 32]]) },
],
valuePrefix: '$',
isUtc: true,
});
```
Like a line, a step dataset can be dashed or dotted, and breaks at `null` values. Steps also make a good limit or budget over a bar chart: see [Mixing types](#mixing-types).
## Pie
A pie shows the parts of a whole as sectors of a circle. It sums each dataset's values over the labels on screen, so with many labels and a minimap, the reader picks the period it sums:
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
const channels = ['Chat', 'Email', 'Phone', 'Forum'];
new LovelyChart(document.getElementById('chart'), {
title: 'Support tickets',
type: 'pie',
labels: days(90),
datasets: channels.map((name, i) => ({
name,
values: series(90, { start: 400 / (i + 1), seasonality: 0.2, seed: 40 + i }),
})),
withMinimap: true,
isUtc: true,
});
```
- Drag the minimap window to sum another period; the sectors animate to their new sizes.
- Each sector large enough shows its share as a percentage, in white, or in a dark grey on a sector too pale for white, as a checked legend button labels its colour. Point at a sector to pull it out, and the tooltip shows that sector alone.
- For one total per dataset, use a single text label: see [Pie and donut of totals](https://lovelychart.io/guide/data.md#pie-and-donut-of-totals).
- Reference lines, hatched ranges, event lines and the `comparison` line don't apply to pies and donuts.
Keep a pie to a handful of datasets: small sectors are hard to compare, and a stacked bar or area shows many parts better.
## Donut
A donut is a pie with a hole in the middle. [`withGradient`](https://lovelychart.io/guide/api.md#withGradient) shades each sector from 10% lighter at its inner edge to 10% darker at its outer edge:
```js
import LovelyChart from 'lovely-chart';
// One day of sales of six fruits
const data = await fetch('../data/donut.json').then((r) => r.json());
new LovelyChart(document.getElementById('chart'), {
...data,
title: 'Fruit sales',
type: 'donut',
withGradient: true,
});
```
`withGradient` shades a pie the same way, from its centre, and the pie or donut that a [zoom into shares](https://lovelychart.io/guide/zoom.md) opens too.
## Mixing types
A dataset's [`type`](https://lovelychart.io/guide/api.md#datasets-type), `line`, `bar` or `step`, draws it as another type than the chart's: a line over bars, say, or steps over a stack of areas.
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
const orders = series(60, { start: 820, seasonality: 0.25, seed: 11 });
// The mean of each day and the six before it, none until a week has passed
const average = orders.map((_, i) => (
i < 6 ? null : Math.round(orders.slice(i - 6, i + 1).reduce((sum, value) => sum + value, 0) / 7)
));
new LovelyChart(document.getElementById('chart'), {
title: 'Orders',
type: 'bar',
labels: days(60),
datasets: [
{ name: 'Orders', color: '#9ED448', values: orders },
{ name: '7-day average', type: 'line', color: '#2373DB', values: average },
],
isUtc: true,
});
```
- Lines and steps draw over bars and areas, whatever the order of `datasets`.
- A chart with bars or steps among its datasets gives every label a column, and its lines run through the middles of the columns.
- A dataset of another type than the chart's draws its own values. It stays out of a stacked chart's stack, the tooltip's total, the `comparison` and the shares of a zoom into a label, so a target or a budget never adds to the total.
- `type` is ignored on percentage, pie and donut charts, whose datasets are all shares of one whole.
## A second Y axis
[`hasSecondYAxis`](https://lovelychart.io/guide/api.md#hasSecondYAxis) puts the last dataset on a Y axis of its own, labelled at the right of the plot in the dataset's colour. Use it for two measures of different scales, such as a count and a rate:
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
new LovelyChart(document.getElementById('chart'), {
title: 'Sessions and bounce rate',
type: 'line',
labels: days(60),
datasets: [
{ name: 'Sessions', values: series(60, { start: 5400, seasonality: 0.15, seed: 5 }) },
{ name: 'Bounce rate, %', values: series(60, { start: 42, volatility: 0.03, decimals: 1, seed: 6 }) },
],
hasSecondYAxis: true,
isUtc: true,
});
```
- The main Y axis takes the colour of the first dataset, so each axis reads as its dataset's. On a stacked or percentage chart, the main axis keeps the axis text colour.
- The last dataset stays out of the main Y axis and the tooltip's total, and on a stacked chart it draws beside the stack rather than in it.
- `valuePrefix` and `valueSuffix` go on the main axis labels and on every dataset's value in the tooltip, while the second axis shows bare numbers. So name the unit of the second axis in its dataset's `name`, as `Bounce rate, %` here.
To label the main axis in a second unit instead, such as a currency, see [`secondaryYAxis`](https://lovelychart.io/guide/api.md#secondaryYAxis) in [A second unit on the same axis](https://lovelychart.io/guide/axes.md#a-second-unit-on-the-same-axis). [Axes](https://lovelychart.io/guide/axes.md#a-second-y-axis) has more on the second Y axis.
## Sparklines
[`isSparkline`](https://lovelychart.io/guide/api.md#isSparkline) draws the datasets alone, inset by 2px: no axes, grid, header or legend. With a small [`plotHeight`](https://lovelychart.io/guide/api.md#plotHeight), it fits a table row or a card.
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
new LovelyChart(document.getElementById('chart'), {
type: 'area',
labels: days(30),
datasets: [{
name: 'Revenue',
color: '#5FB641',
values: series(30, { start: 4200, trend: 0.01, seed: 7 }),
}],
isSparkline: true,
plotHeight: 48,
areaOpacity: 0.25,
areaBorderColor: '#5FB641',
isUtc: true,
});
```
- Any type can be a sparkline. A line or a translucent area, as here, reads best at this size.
- The bottom of the Y range isn't rounded to an axis step: it's 0, unless the values go below 0 or their lowest is more than three quarters of their highest.
- When the row around a sparkline already names it, set [`ariaLabel: ''`](https://lovelychart.io/guide/api.md#ariaLabel) to leave the plot out of the accessibility tree. See [Accessibility](https://lovelychart.io/guide/accessibility.md).
---
# Axes and values
Every chart but a pie, a donut and a sparkline draws a Y axis of values and an X axis of labels. This page shows how the chart picks the Y range and its steps, how values read on the axis and in the tooltip, how to add a second unit or a second axis, and how to place and style the labels.
## The Y axis range
You don't set the Y range yourself: the chart fits it to the data on screen, and fits it again, with an animation, whenever that changes.
- It covers the datasets shown, over the labels the plot shows. Pan the [minimap](https://lovelychart.io/guide/minimap.md) or hide a dataset in the [legend](https://lovelychart.io/guide/legend.md), and the range follows.
- A chart that doesn't stack starts at 0, unless the values go below 0 or their lowest is more than three quarters of their highest. A line between 20 and 90 starts at 0, while one between 80 and 90 starts near 80, so a small change stays visible.
- A stacked chart always spans 0, and so does an axis that bars share with lines or steps, so that heights compare.
- A percentage chart always spans 0–100%.
- The bottom of the range rounds down to an axis step, so the lowest grid line is labelled.
The axis steps in round numbers, 1, 2 or 5 times a power of ten (2.5 in place of 2 from 250 up), as many as the plot height has room for. A short plot takes a finer step, so at least two labels stay legible. The labels shorten thousands, millions, billions and trillions to `K`, `M`, `B` and `T`, with as many digits after the point as the step needs: `6.25K` in steps of 250, `6K` in steps of 1,000.
### Whole-number steps
For counts, a step of 0.5 makes no sense: a range of 0 to 2 would read 0, 0.5, 1, 1.5 and 2. Set `noFloatSteps: true` to step the main and the second Y axis in whole numbers, 1 at the finest:
```js
import LovelyChart from 'lovely-chart';
import { days } from './demo-data.js';
new LovelyChart(document.getElementById('chart'), {
title: 'Production deploys',
type: 'bar',
labels: days(14),
datasets: [
{ name: 'Deploys', color: '#5FB641', values: [1, 0, 2, 1, 1, 0, 0, 2, 1, 2, 1, 0, 0, 1] },
],
noFloatSteps: true,
isUtc: true,
});
```
### Pinning the range
A [reference line](https://lovelychart.io/guide/annotations.md#reference-lines) always stays inside the Y range, and one with `color: 'transparent'` draws nothing, so it's the way to pin an end of the axis. Pin both ends to keep one scale while the reader pans, as for a load that can't pass 100%:
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
new LovelyChart(document.getElementById('chart'), {
title: 'CPU load',
type: 'line',
labels: days(90),
datasets: [
{ name: 'web-1', values: series(90, { start: 42, volatility: 0.07, seasonality: 0.1, seed: 3 }) },
{ name: 'web-2', values: series(90, { start: 55, volatility: 0.07, seasonality: 0.1, seed: 8 }) },
],
valueSuffix: '%',
// The axis reads 0–100% wherever the window is
referenceLines: [
{ value: 0, color: 'transparent' },
{ value: 100, color: 'transparent' },
],
withMinimap: true,
isUtc: true,
});
```
Pin one end alone to start at 0 a range that would otherwise start near its lowest value. A visible reference line, such as a target, stays in view the same way: see [Annotations](https://lovelychart.io/guide/annotations.md#pinning-the-y-range).
> [!NOTE]
> On a percentage chart the range stays 0–100% whatever the reference lines, and their `value` is a percentage.
## Formatting values
The chart formats a number in two ways:
| Where | By default | Options |
|---|---|---|
| Y-axis labels | Short: `12.5K`, `3M` | `valuePrefix`, `valueSuffix`, `isCurrencyPrefix` |
| Tooltip values and totals | In full, thousands set apart by a space, with no trailing zeros: `12 500`, `3.25` | `formatTooltipValue`, `valuePrefix`, `valueSuffix`, `isCurrencyPrefix` |
[`onTooltipChange`](https://lovelychart.io/guide/api.md#onTooltipChange) hands you the raw numbers, to format as you like on the page: see [Tooltip](https://lovelychart.io/guide/tooltip.md#your-own-readout).
### Prefixes and suffixes
[`valuePrefix`](https://lovelychart.io/guide/api.md#valuePrefix) and [`valueSuffix`](https://lovelychart.io/guide/api.md#valueSuffix) wrap every formatted value: the main Y-axis labels, the tooltip values and its totals. Include any space you want, as `valueSuffix: ' ms'`.
They leave out two kinds of labels: those of a [second Y axis](#a-second-y-axis), which show bare numbers, and those of a [second unit](#a-second-unit-on-the-same-axis), which take a prefix and a suffix of their own.
### Negative amounts of money
A prefix goes before the sign by default, as `$-9.1`. For a currency, set [`isCurrencyPrefix`](https://lovelychart.io/guide/api.md#isCurrencyPrefix) to put the minus sign first, as `-$9.1`:
```js
import LovelyChart from 'lovely-chart';
const data = await fetch('../data/bars-negative.json').then((response) => response.json());
new LovelyChart(document.getElementById('chart'), {
...data,
title: 'Daily P&L',
// The values are in thousands of dollars
valuePrefix: '$',
valueSuffix: 'K',
isCurrencyPrefix: true,
isUtc: true,
});
```
The flag moves the sign in front of the `prefix` of [`secondaryYAxis`](#a-second-unit-on-the-same-axis) too.
### Formatting tooltip numbers
[`formatTooltipValue`](https://lovelychart.io/guide/api.md#formatTooltipValue) takes a number of the tooltip and returns its text. `valuePrefix` and `valueSuffix` still wrap the result, and the axis labels keep their short form:
```js
new LovelyChart(element, {
type: 'line',
labels,
datasets: [{ name: 'Average', values: temperatures }],
valueSuffix: ' °C',
// 16 reads 16.0, like its neighbours
formatTooltipValue: (value) => value.toFixed(1),
});
```
`(value) => value.toLocaleString('en-US')` groups thousands with commas, as `12,500`. The function formats the total on the [`secondaryYAxis`](#a-second-unit-on-the-same-axis) scale too.
## A second unit on the same axis
When the values convert into another unit by a factor, such as energy into its cost, [`secondaryYAxis`](https://lovelychart.io/guide/api.md#secondaryYAxis) labels the main Y axis in that unit too, at the right of the plot. It takes a `label`, a `multiplier`, and an optional `prefix` and `suffix`:
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
new LovelyChart(document.getElementById('chart'), {
title: 'Energy use',
type: 'bar',
isStacked: true,
labels: days(30),
datasets: [
{ name: 'Heating', values: series(30, { start: 21, volatility: 0.1, decimals: 1, seed: 2 }) },
{ name: 'Hot water', values: series(30, { start: 8, volatility: 0.1, decimals: 1, seed: 6 }) },
{ name: 'Appliances', values: series(30, { start: 6, volatility: 0.1, decimals: 1, seed: 9 }) },
],
valueSuffix: ' kWh',
// €0.30 per kWh
secondaryYAxis: { label: 'Cost', multiplier: 0.3, prefix: '€' },
isUtc: true,
});
```
The tooltip adds a row of `label` with the total times `multiplier`: under the Total row of a stacked or percentage bar, step or area chart, as here, and under the dataset rows of any other chart. A percentage chart's axis has no scale at the right.
## A second Y axis
When the last dataset has a unit or a magnitude of its own, such as a rate beside counts, set [`hasSecondYAxis`](https://lovelychart.io/guide/api.md#hasSecondYAxis) to put it on an axis of its own:
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
new LovelyChart(document.getElementById('chart'), {
title: 'Visitors and conversion',
type: 'bar',
labels: days(30),
datasets: [
{ name: 'Visitors', color: '#3497ED', values: series(30, { start: 12400, seasonality: 0.15, seed: 1 }) },
{
name: 'Conversion, %',
type: 'line',
color: '#F79E39',
values: series(30, { start: 2.8, volatility: 0.05, decimals: 1, seed: 12 }),
},
],
hasSecondYAxis: true,
isUtc: true,
});
```
- The last dataset is labelled at the right of the plot, in its colour.
- The main axis is labelled in the colour of the first dataset, apart from a stacked or percentage chart's, which keeps the axis text colour.
- The last dataset stays out of the main Y axis, the tooltip's total and, on a stacked chart, the stack.
> [!TIP]
> The labels of the second axis show bare numbers, while every tooltip row takes `valuePrefix` and `valueSuffix`. Name the unit in the dataset's name, as `Conversion, %` above, rather than in a suffix the other datasets would take too.
## Label placement and look
| Option | Does |
|---|---|
| [`isYAxisOutward`](https://lovelychart.io/guide/api.md#isYAxisOutward) | Moves the main Y-axis labels into a column left of the plot, right-aligned, so the data never runs under them |
| [`areLabelsContrast`](https://lovelychart.io/guide/api.md#areLabelsContrast) | Draws each Y-axis label in a halo of the background colour, 2px in from its side of the chart |
| [`axisFontSize`](https://lovelychart.io/guide/api.md#axisFontSize) | Font size of the labels of both axes in px, `10` by default |
| [`axisTextColor`](https://lovelychart.io/guide/api.md#axisTextColor) | Colour of the labels of both axes: a CSS colour, or `{ light, dark }` for each skin |
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
new LovelyChart(document.getElementById('chart'), {
title: 'Page views',
type: 'line',
labels: days(60),
datasets: [
{
name: 'Views',
color: '#2373DB',
values: series(60, { start: 148000, trend: 0.003, seasonality: 0.12, seed: 5 }),
},
],
isYAxisOutward: true,
areLabelsContrast: true,
axisFontSize: 12,
axisTextColor: { light: '#2373DB', dark: '#7FB8F0' },
isUtc: true,
});
```
The column of `isYAxisOutward` fits the widest label the chart can show for its data, at any window and with any datasets hidden, so the plot holds still while the reader pans. The chart measures it when it builds, on `update()` and on a zoom, and again once a web font of the page changes the axis font. A second Y axis keeps its labels inside the plot.
Each Y-axis label stands on the row above its grid line. With `areLabelsContrast`, the labels of both axes stand 2px in from their side of the chart, which keeps the halo of a label inside the plot whole at the plot edge, and the column of `isYAxisOutward` grows by those 2px. The labels of [hatched ranges](https://lovelychart.io/guide/annotations.md#labels-and-edges) and [event lines](https://lovelychart.io/guide/annotations.md#labels-and-hints) keep clear of the Y-axis labels, that inset included.
The labels take the font family and the regular weight of the chart's text, from the [`--lovely-chart-font-family`](https://lovelychart.io/guide/css.md#--lovely-chart-font-family) and [`--lovely-chart-font-weight`](https://lovelychart.io/guide/css.md#--lovely-chart-font-weight) CSS variables: see [Theming](https://lovelychart.io/guide/theming.md).
> [!NOTE]
> [`backgroundColor`](https://lovelychart.io/guide/api.md#backgroundColor) gives the Y-axis labels a halo of that colour too, so they stay legible over the data. Without it, only `areLabelsContrast` labels get one.
## The X axis
The X axis shows your [`labels`](https://lovelychart.io/guide/api.md#labels): dates for timestamps, or the text itself for strings. It always shows the newest label, spaces the others evenly back from it, and takes a coarser step when they would crowd, keeping the labels at the edges inside the plot. `axisFontSize` and `axisTextColor` apply to it as to the Y axis, and it runs left to right on a right-to-left page too.
How a timestamp reads, in which time zone and in which language, is the subject of [Dates, time zones and locales](https://lovelychart.io/guide/dates.md).
---
# Dates, time zones and locales
Most charts run along time. This page shows how the chart turns timestamps into labels, how to pick their format and time zone, when to use text labels instead, what the header caption says, and how to show dates in another language or on a right-to-left page.
## Timestamp labels
[`labels`](https://lovelychart.io/guide/api.md#labels) holds UNIX timestamps in milliseconds, one per value. The chart picks the kind of label from the step between the first two of them, unless you set [`labelType`](https://lovelychart.io/guide/api.md#labelType):
| `labelType` | Inferred from a step of | Axis label | Reads in |
|---|---|---|---|
| `year` | 365 days or more | `2026` | UTC |
| `month` | 28 days or more | `January` | UTC |
| `week` | 7 days or more | `Week 1` | UTC |
| `day` | a day or more | `18 Nov` | The reader's time zone, or UTC with `isUtc` |
| `hour` | an hour or more | `14:00` | The reader's time zone, or UTC with `isUtc` |
| `5min` | less than an hour | `14:05` | The reader's time zone, or UTC with `isUtc` |
| `dayHour` | never inferred | `18 Nov 14:00` | The reader's time zone, or UTC with `isUtc` |
| `text` | strings, not timestamps | The string itself | — |
- A `week` label is the ISO 8601 week number of the label's UTC date, so 29 Dec 2025 reads `Week 1` and 28 Dec 2026 `Week 53`.
- A single timestamp, as in a pie of one period, counts as `day`.
- `labelType` sets the granularity of the [header caption](#the-header-caption) too: a year chart reads `2022 — 2026`, a month chart `February — March 2029`.
Set `labelType` yourself for `dayHour`, which the chart never infers, or when the step between the first two labels isn't the step of the data.
## Label and tooltip formats
### Axis label formats
[`labelFormatter`](https://lovelychart.io/guide/api.md#labelFormatter) gives the X-axis labels another format than the one of `labelType`, while the caption keeps the granularity of `labelType`. It takes one of these strings:
| `labelFormatter` | Reads |
|---|---|
| `'statsFormatYear'` | `2026` |
| `'statsFormatMonth'` | `January` |
| `'statsFormatWeek'` | `Week 1` |
| `"statsFormat('day')"` | `18 Nov` |
| `"statsFormat('hour')"` or `"statsFormat('5min')"` | `14:00` |
| `'statsFormatDayHour'` | `18 Nov 14:00` |
The quotes inside are part of the string: write `"statsFormat('day')"`, not `statsFormat('day')` or `'day'`.
The most common use labels weekly data by the date each week starts on, in place of week numbers:
```js
import LovelyChart from 'lovely-chart';
import { series } from './demo-data.js';
const WEEK = 7 * 24 * 60 * 60 * 1000;
// 16 Mondays at UTC midnight, from 6 Jul 2026
const labels = Array.from({ length: 16 }, (_, i) => Date.UTC(2026, 6, 6) + i * WEEK);
new LovelyChart(document.getElementById('chart'), {
title: 'Weekly sign-ups',
type: 'bar',
labels,
datasets: [
{ name: 'Sign-ups', color: '#5FB641', values: series(16, { start: 1800, trend: 0.02, seed: 14 }) },
],
labelFormatter: "statsFormat('day')",
tooltipFormatter: "statsTooltipFormat('week')",
isUtc: true,
});
```
`isUtc: true` matters here: the day format follows the reader's time zone, where a Monday at UTC midnight is still Sunday for a reader west of UTC. See [Time zones](#time-zones).
### Tooltip title formats
The tooltip title is the X-axis label, unless [`tooltipFormatter`](https://lovelychart.io/guide/api.md#tooltipFormatter) gives it a format of its own:
| `tooltipFormatter` | Reads |
|---|---|
| `"statsTooltipFormat('day')"` | `18 Nov 2026` |
| `"statsTooltipFormat('week')"` | `Week of 16 Nov` |
| `"statsTooltipFormat('hour')"` or `"statsTooltipFormat('5min')"` | `14:00` |
| `'statsFormatDayHourFull'` | `18 Nov 14:00` |
Use it to add what the axis leaves out: the year of a day, or the day of an hour. Here the axis shows the hours, and the tooltip the day with them:
```js
import LovelyChart from 'lovely-chart';
import { hours, series } from './demo-data.js';
new LovelyChart(document.getElementById('chart'), {
title: 'API requests',
type: 'line',
labels: hours(72),
datasets: [
{
name: 'Requests',
values: series(72, { start: 5200, volatility: 0.05, seasonality: 0.35, period: 24, seed: 9 }),
},
],
tooltipFormatter: 'statsFormatDayHourFull',
withMinimap: true,
});
```
This chart has no `isUtc`, so its hours read in your own time zone.
## Time zones
A timestamp is a moment, and the day or the hour it falls on depends on the time zone. Some texts follow [`isUtc`](https://lovelychart.io/guide/api.md#isUtc), and the others always read UTC:
| Reads in the reader's time zone, or in UTC with `isUtc: true` | Always reads in UTC |
|---|---|
| Axis labels of `day`, `hour`, `5min` and `dayHour`, and the tooltip titles that repeat them | Axis labels of `year`, `month` and `week` |
| Tooltip titles of `"statsTooltipFormat('hour')"`, `"statsTooltipFormat('5min')"` and `'statsFormatDayHourFull'` | Tooltip titles of `"statsTooltipFormat('day')"` and `"statsTooltipFormat('week')"` |
| | The header caption |
Which to choose:
- **Daily or weekly data stamped at UTC midnight**, as most servers send it: set `isUtc: true`. Without it, a reader west of UTC sees each day labelled as the day before, under a caption that names the right days.
- **Hourly data:** leave `isUtc` unset to show each reader their own clock, or set it to show everyone the same UTC hours, and say so in the title.
> [!TIP]
> The demo data of these docs, `days()`, `hours()` and `months()`, is stamped in UTC, which is why most examples set `isUtc: true`.
## Text labels
Strings in `labels` make text labels, `labelType: 'text'`. The axis and the tooltip title show them as they are, and the header shows no caption: the `title` alone, or nothing with no title.
```js
import LovelyChart from 'lovely-chart';
new LovelyChart(document.getElementById('chart'), {
title: 'Orders by weekday',
type: 'bar',
isStacked: true,
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
datasets: [
{ name: 'Web', values: [412, 438, 451, 470, 502, 365, 298] },
{ name: 'App', values: [286, 301, 296, 318, 344, 402, 379] },
],
});
```
- Where a callback takes the value of a label, such as [`onZoom`](https://lovelychart.io/guide/api.md#onZoom), [`onZoomChange`](https://lovelychart.io/guide/api.md#onZoomChange) and [`resolveTooltipNotes`](https://lovelychart.io/guide/api.md#resolveTooltipNotes), a text label's value is its index in `labels`.
- A pie or a donut of one total per dataset takes a single text label, as `labels: ['Total']`: see [Chart types](https://lovelychart.io/guide/chart-types.md).
## The header caption
The caption at the end of the header names the dates on screen, at the granularity of `labelType`, and follows the reader as they pan and zoom:
| Labels | The window holds | Caption |
|---|---|---|
| Days, weeks or hours | Several days | `1 Nov — 30 Nov`, or `1 Jan 2026 — 18 Feb 2027` across years |
| Days or hours | One day | `Friday, 6 Nov` |
| Months | Several months | `February — March 2029` |
| Months | One month | `April 2029` |
| Years | Several years | `2022 — 2026` |
The year is left out when it's the current one for both ends. The caption always reads UTC, in the language of [`dateLocale`](#localized-names).
To leave it out, set [`noCaption: true`](https://lovelychart.io/guide/api.md#noCaption). It stays out while zoomed too, with no `noCaption` needed in the data [`onZoom`](https://lovelychart.io/guide/zoom.md#loading-detail-data) returns. With no `title` either, the header has nothing to show and folds to [`--lovely-chart-empty-header-height`](https://lovelychart.io/guide/css.md#--lovely-chart-empty-header-height), 0 by default, so the plot starts at the top of the chart. See [Layout](https://lovelychart.io/guide/layout.md) for the header itself.
## Localized names
[`dateLocale`](https://lovelychart.io/guide/api.md#dateLocale) gives the names in dates in another language: `{ months, monthsFull, weekDays, weekDaysShort, weekOf }`. Each field is optional and falls back to English.
| Field | Holds | Shows in |
|---|---|---|
| `months` | 12 short month names, from January | Day and day-hour labels (`18 Nov`), the day and week tooltip titles, the caption of days |
| `monthsFull` | 12 full month names, from January | Month labels (`January`) and the caption of months (`April 2029`) |
| `weekDays`, `weekDaysShort` | 7 weekday names, full and short, from Sunday | The full ones name the day in the caption of a single day (`Friday, 6 Nov`) |
| `weekOf` | The words before the date in a week title | `Week of 16 Nov`, from `"statsTooltipFormat('week')"` |
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
const es = {
months: ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sept', 'oct', 'nov', 'dic'],
monthsFull: [
'enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio',
'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre',
],
weekDays: ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'],
weekDaysShort: ['dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb'],
weekOf: 'Semana del',
};
new LovelyChart(document.getElementById('chart'), {
title: 'Reservas diarias',
type: 'line',
labels: days(90),
datasets: [{ name: 'Reservas', values: series(90, { start: 340, seasonality: 0.2, seed: 21 }) }],
dateLocale: es,
tooltipFormatter: "statsTooltipFormat('day')",
withMinimap: true,
isUtc: true,
});
```
A few texts of the chart stay in English whatever `dateLocale` says, and each has its own way out:
- `week` labels read `Week 1`: label weeks by the day they start on with `labelFormatter: "statsFormat('day')"`, [as above](#axis-label-formats).
- The Total row of the tooltip is named `Total`: [`isTooltipTotalInTitle`](https://lovelychart.io/guide/api.md#isTooltipTotalInTitle) puts the total beside the title, with no name.
- The zoom-out control reads `Zoom out`: set [`zoomOutLabel`](https://lovelychart.io/guide/api.md#zoomOutLabel).
- The plot's accessible name is an English summary of the data: set [`ariaLabel`](https://lovelychart.io/guide/api.md#ariaLabel). See [Accessibility](https://lovelychart.io/guide/accessibility.md).
The axis labels keep `K`, `M`, `B` and `T` for thousands and up. For the numbers of the tooltip in the reader's language, use [`formatTooltipValue`](https://lovelychart.io/guide/axes.md#formatting-tooltip-numbers) with `toLocaleString()`.
## Right-to-left pages
Put the chart in an element with `dir="rtl"`, or on a page whose `` has it, and the chart lays out from the right: the title at the right of the header and the caption at the left, the legend from the right, and the swatch and the name of each tooltip row before its value.
What reads in which direction:
- **The plot, the X axis and the minimap** run left to right on any page, the earliest label at the left.
- **Dates and text labels**, on the X axis, in the header caption and in the tooltip title, read in the direction of their first letter, whatever the direction of the page: English dates left to right, and dates in Hebrew or Arabic words right to left. With no letter, as in `2022 — 2026`, they read left to right, the way the X axis runs.
- **Numbers** read left to right, each sign before its digits: the Y-axis labels, and the values, the totals and the shares of the tooltip.
- **Reference line labels** read in the direction of the page: see [Annotations](https://lovelychart.io/guide/annotations.md#reference-lines) to keep a sign first.
```js
import LovelyChart from 'lovely-chart';
const element = document.getElementById('chart');
element.dir = 'rtl';
element.lang = 'he';
const data = await fetch('../data/bars-negative.json').then((response) => response.json());
const names = ['הכנסות', 'החזרים', 'התאמות'];
new LovelyChart(element, {
...data,
title: 'רווח והפסד יומי',
datasets: data.datasets.map((dataset, i) => ({ ...dataset, name: names[i] })),
dateLocale: {
months: ['ינו׳', 'פבר׳', 'מרץ', 'אפר׳', 'מאי', 'יוני', 'יולי', 'אוג׳', 'ספט׳', 'אוק׳', 'נוב׳', 'דצמ׳'],
monthsFull: [
'ינואר', 'פברואר', 'מרץ', 'אפריל', 'מאי', 'יוני', 'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר',
],
weekDays: ['יום ראשון', 'יום שני', 'יום שלישי', 'יום רביעי', 'יום חמישי', 'יום שישי', 'יום שבת'],
weekDaysShort: ['יום א׳', 'יום ב׳', 'יום ג׳', 'יום ד׳', 'יום ה׳', 'יום ו׳', 'שבת'],
},
// The Total row is named in English, so the total goes beside the title
isTooltipTotalInTitle: true,
isUtc: true,
});
```
The dates read right to left, as their first letter is Hebrew, while the negative values keep their minus signs before the digits.
---
# Tooltip
Point at a label, or touch it, and the chart shows its values in a balloon beside the pointer. This page covers what the balloon shows and in what order, its totals and notes, a readout of your own in its place, and how to style it or turn it off.
## What the tooltip shows
From top to bottom, the balloon holds:
1. **The title**: the label as the X axis shows it, or in the format of [`tooltipFormatter`](https://lovelychart.io/guide/dates.md#tooltip-title-formats). A [title note](#notes) can follow it, and with `isTooltipTotalInTitle` the [total](#totals) stands at its far end. On a chart that [zooms](https://lovelychart.io/guide/zoom.md), a chevron at the end of the title shows that a click zooms in.
2. **The comparison row**, on a chart with a [`comparison`](https://lovelychart.io/guide/annotations.md#comparison-with-a-previous-period): the value of the previous period in a muted colour, with the change of the current total in percent, set apart from the rows under it by a rule.
3. **A row for each dataset on screen** with a value at the label: a swatch of its colour, its name and its value, from the largest value down. The swatch of a dashed or dotted line is a dashed or dotted outline. A dataset hidden in the legend, or with a gap or a zero at the label, has no row, and the balloon holds 12 rows at most.
4. **The Total row**, on a stacked or percentage bar, step or area chart.
5. **The row of a second unit**, with a [`secondaryYAxis`](https://lovelychart.io/guide/axes.md#a-second-unit-on-the-same-axis).
6. **Notes**, under a rule: see [Notes](#notes).
A percentage chart prints the share of each dataset at the start of its row. A pie or a donut lists the sector under the pointer alone.
On the plot, a line or an area chart draws a vertical line at the label, a chart with bars or steps masks the columns around the focused one instead, and each line dataset gets a dot at the label.
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
// Eight weeks of visits: the last four on the chart, the four before as the comparison
const channels = [['Search', 5200, 1], ['Direct', 3100, 2], ['Social', 1900, 3], ['Email', 900, 4]]
.map(([name, start, seed]) => ({ name, values: series(56, { start, seasonality: 0.15, seed }) }));
new LovelyChart(document.getElementById('chart'), {
title: 'Visits by channel',
type: 'bar',
isStacked: true,
labels: days(28),
datasets: channels.map(({ name, values }) => ({ name, values: values.slice(28) })),
comparison: { name: 'Four weeks before', values: channels.map(({ values }) => values.slice(0, 28)) },
isUtc: true,
});
```
## Formatting values
The tooltip prints each number in full, its thousands set apart by a space, as `12 500`. These options change that:
```js
new LovelyChart(element, {
...params,
// Wraps every value and total of the tooltip, and the Y-axis labels
valuePrefix: '$',
// -$9.1 rather than $-9.1, on the Y axis too
isCurrencyPrefix: true,
// The number between the prefix and the suffix, in the tooltip alone
formatTooltipValue: (value) => value.toLocaleString('en-US', { maximumFractionDigits: 1 }),
});
```
See [Formatting values](https://lovelychart.io/guide/axes.md#formatting-values) for each of them, and [`valueSuffix`](https://lovelychart.io/guide/api.md#valueSuffix) for units after the number.
## Totals
A stacked or percentage `bar`, `step` or `area` chart adds a Total row: the sum of the rows on screen. A dataset on a [second Y axis](https://lovelychart.io/guide/axes.md#a-second-y-axis), or drawn as [another type](https://lovelychart.io/guide/api.md#datasets-type) than the chart's, stays out of it. Two options change where the total stands and what it is:
- [`isTooltipTotalInTitle`](https://lovelychart.io/guide/api.md#isTooltipTotalInTitle) puts the total at the end of the title, in place of the Total row.
- [`resolveTooltipTotal`](https://lovelychart.io/guide/api.md#resolveTooltipTotal) gives the total yourself, for a total that isn't the sum of its parts. It takes `(labelValue, datasetIndexes, labelIndex)`: the label's timestamp, or the index of a text label, the indexes of the datasets on screen, and the label's index. Return a number, `null` to show `—`, or `undefined` to keep the sum.
Here a person active on more than one platform counts once in the total, which holds while every platform is shown:
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
const labels = days(30);
const ios = series(30, { start: 4200, seed: 61 });
const android = series(30, { start: 5300, seed: 62 });
const web = series(30, { start: 2700, seed: 63 });
// People on more than one platform count once
const uniqueUsers = labels.map((_, i) => Math.round((ios[i] + android[i] + web[i]) * 0.86));
new LovelyChart(document.getElementById('chart'), {
title: 'Active users',
type: 'bar',
isStacked: true,
labels,
datasets: [
{ name: 'iOS', values: ios },
{ name: 'Android', values: android },
{ name: 'Web', values: web },
],
isTooltipTotalInTitle: true,
// With a platform hidden, the sum of the rows stands
resolveTooltipTotal: (labelValue, datasetIndexes, labelIndex) => (
datasetIndexes.length === 3 ? uniqueUsers[labelIndex] : undefined
),
isUtc: true,
});
```
The change against a [`comparison`](https://lovelychart.io/guide/api.md#comparison) and the total on a [`secondaryYAxis`](https://lovelychart.io/guide/api.md#secondaryYAxis) scale read this total too.
On a percentage chart, the share at the start of each row is a whole percent by default. Where shares sit close together, [`percentPrecision`](https://lovelychart.io/guide/api.md#percentPrecision) adds digits after the point:
```js
new LovelyChart(element, {
type: 'area',
isPercentage: true,
labels,
datasets,
// 12.5% rather than 13%
percentPrecision: 1,
});
```
## Row order
The rows run from the largest value down, so they change places as the reader moves along the labels. On a stacked chart, where the order of the stack means something, [`isTooltipOrderFixed`](https://lovelychart.io/guide/api.md#isTooltipOrderFixed) lists them in the order of the legend instead, after the comparison row:
```js
new LovelyChart(element, {
type: 'area',
isStacked: true,
labels,
datasets,
isTooltipOrderFixed: true,
isTooltipTotalInTitle: true,
});
```
When more than 12 rows would show, the largest values still decide which ones do.
## Notes
Notes are muted lines under the rows, and a muted word or two beside the title, that explain a label: an estimate, an outage, a promotion. They come from three places, in this order:
1. The `note` of each of the [`hatchedRanges`](https://lovelychart.io/guide/annotations.md#notes-in-the-tooltip) that hold the label, and the `titleNote` of the first one that has one.
2. The `hint` of each of the [`eventLines`](https://lovelychart.io/guide/annotations.md#event-lines) at the label.
3. [`resolveTooltipNotes`](https://lovelychart.io/guide/api.md#resolveTooltipNotes), a function of `(labelValue, datasetIndexes, labelIndex)`, as `resolveTooltipTotal` takes them, that returns `{ titleNote?, notes? }` or `undefined`.
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
const promoDays = [18, 19, 20, 21];
new LovelyChart(document.getElementById('chart'), {
title: 'Orders',
type: 'bar',
labels: days(30),
datasets: [{ name: 'Orders', values: series(30, { start: 640, seasonality: 0.2, seed: 71 }) }],
// The last three days are still being counted
hatchedRanges: [{
from: 27,
to: 29,
label: 'Partial',
titleNote: 'partial',
note: 'Late orders are still arriving',
}],
eventLines: [{
labelIndex: 10,
label: 'Outage',
isDashed: true,
hint: 'Checkout was down\nfor 40 minutes',
}],
resolveTooltipNotes: (labelValue, datasetIndexes, labelIndex) => (
promoDays.includes(labelIndex) ? { titleNote: 'promo', notes: ['Autumn sale: 15% off'] } : undefined
),
isUtc: true,
});
```
- A `\n` splits a note into lines, and a line shown already is left out.
- Notes show as text, never as HTML.
- The `titleNote` of `resolveTooltipNotes` wins over that of a range.
- The notes change with the rows, for a pointer, a touch or [`selectLabel()`](https://lovelychart.io/guide/api.md#selectLabel). Pie and donut charts show none.
## Your own readout
To show the tooltip's content somewhere else on the page, such as a panel under the chart on a phone, use [`onTooltipChange`](https://lovelychart.io/guide/api.md#onTooltipChange). The chart calls it whenever what the tooltip shows changes, as another label is selected or a dataset is shown or hidden, and with `undefined` once nothing is selected. It passes:
| Field | Holds |
|---|---|
| `labelIndex` | The index of the label in `labels` |
| `title` | The title of the tooltip |
| `rows` | Each dataset on screen, in the order of `datasets`, as `{ datasetIndex, name, value }`: a zero included, and `null` for a gap |
| `total` | On a stacked or percentage bar, step or area chart, the total the tooltip shows |
| `comparison` | With a `comparison`, `{ name, value, change? }`: the previous value and the change in percent, unrounded |
A pie or a donut reports nothing.
Then hide the balloon with the [`--lovely-chart-balloon-display`](https://lovelychart.io/guide/css.md#--lovely-chart-balloon-display) CSS variable. `none`, on the chart's element or an ancestor, hides the balloon alone: the hover line, the dots, the focus of a bar and the callbacks all stay.
```html
```
To swap the balloon for the readout on narrow screens alone, set the variable in a media query:
```css
@media (max-width: 40rem) {
.readout-chart {
--lovely-chart-balloon-display: none;
}
}
```
[`isKeyboardSelectable`](https://lovelychart.io/guide/api.md#isKeyboardSelectable), set above, lets the reader step through the labels with the arrow keys. See [Interaction](https://lovelychart.io/guide/interaction.md) for it, for [`onSelectedIndexChange`](https://lovelychart.io/guide/api.md#onSelectedIndexChange) and for selecting a label from the page with `selectLabel()`.
## Styling
The balloon's text takes the `--text-color` of the skin, and its background `--tooltip-background`. A few more variables style the rest:
| Variable | Styles | Default |
|---|---|---|
| [`--tooltip-border`](https://lovelychart.io/guide/css.md#--tooltip-border) | The border of the balloon, as `1px solid #D2D5D7` | `none` |
| [`--tooltip-muted-text-color`](https://lovelychart.io/guide/css.md#--tooltip-muted-text-color) | The comparison row and the notes | A mix of 70% `--text-color` and 30% `--tooltip-background` |
| [`--tooltip-separator-color`](https://lovelychart.io/guide/css.md#--tooltip-separator-color) | The rules under the comparison row and over the notes | `--grid-lines` |
| `--tooltip-change-positive`, `--tooltip-change-negative` | A rise and a fall against the comparison | A blue and a red of the skin |
They're colours of the skin, set on `.lovely-chart--container`, so set yours there too, and one for each skin where day and night differ: see [Theming](https://lovelychart.io/guide/theming.md).
For anything else, the tooltip keeps these classes from release to release; its other classes are internal:
| Class | Element |
|---|---|
| [`.lovely-chart--tooltip-balloon`](https://lovelychart.io/guide/css.md#lovely-chart--tooltip-balloon) | The balloon: its shadow, padding and radius |
| [`.lovely-chart--tooltip-title`](https://lovelychart.io/guide/css.md#lovely-chart--tooltip-title) | The title |
| [`.lovely-chart--tooltip-title-total`](https://lovelychart.io/guide/css.md#lovely-chart--tooltip-title-total) | The total beside the title |
| [`.lovely-chart--tooltip-title-note`](https://lovelychart.io/guide/css.md#lovely-chart--tooltip-title-note) | The note beside the title |
| [`.lovely-chart--tooltip-dataset`](https://lovelychart.io/guide/css.md#lovely-chart--tooltip-dataset) | A row, the comparison, Total and second-unit rows included |
| [`.lovely-chart--tooltip-dataset-value`](https://lovelychart.io/guide/css.md#lovely-chart--tooltip-dataset-value) | The value of a row |
| [`.lovely-chart--tooltip-dataset-comparison`](https://lovelychart.io/guide/css.md#lovely-chart--tooltip-dataset-comparison) | The comparison row |
| [`.lovely-chart--tooltip-swatch`](https://lovelychart.io/guide/css.md#lovely-chart--tooltip-swatch) | The swatch of a row, in `--lovely-chart-series-color` |
| [`.lovely-chart--tooltip-change[data-tone]`](https://lovelychart.io/guide/css.md#lovely-chart--tooltip-change) | The change against the comparison: `positive`, `negative` or `neutral` |
| [`.lovely-chart--tooltip-notes`](https://lovelychart.io/guide/css.md#lovely-chart--tooltip-notes) | The notes under the rows, a `
` per line |
```html
```
> [!TIP]
> Scope your rules to the chart's element, as `#styled-chart` above, so that they win over the library's own rules wherever its stylesheet loads.
## Turning it off
[`noTooltip: true`](https://lovelychart.io/guide/api.md#noTooltip) leaves out the whole hover layer: the line, the dots and the balloon, and the pointer handling of the plot. No pointer selects a label or a range, focuses a bar or zooms in, and `selectLabel()`, `isKeyboardSelectable` and `isRangeSelectable` are ignored. [`initialZoom`](https://lovelychart.io/guide/zoom.md#opening-zoomed) still opens a zoom. It suits small multiples and thumbnails that read at a glance.
To keep the hover line and the callbacks and drop the balloon alone, use `--lovely-chart-balloon-display: none`, as in [Your own readout](#your-own-readout).
## Touch screens
- A touch on the plot selects the label under the finger, and a move along the plot follows it. A touch elsewhere on the page clears it.
- On a chart that zooms, a tap on the balloon zooms into its label, as a click on the plot does with a mouse. With `--lovely-chart-balloon-display: none` there's no balloon to tap, so that zoom goes too.
- A drag across the plot keeps selecting labels: [selecting a range](https://lovelychart.io/guide/minimap.md#selecting-a-range-on-the-plot) on the plot is for a mouse.
---
# Legend
A chart of more than one dataset ends with a legend: a button for each dataset, which hides it or shows it again. This page covers toggling, datasets that start hidden, reacting to the reader's choice, a legend elsewhere on the page, and the look of its buttons.
## Toggling datasets
- A click or a tap on a button hides its dataset, and another shows it again. The plot, the Y range, the minimap and the tooltip follow.
- Press and hold a button for half a second to show its dataset alone. Hold the button of the only dataset on screen to show all the others in its place.
- The last dataset on screen stays: its button shakes rather than hide it, as a chart of nothing would say nothing.
- Each button is in the tab order, with `role="button"` and `aria-pressed`, and toggles on Enter or Space.
A chart with a [`comparison`](https://lovelychart.io/guide/annotations.md#comparison-with-a-previous-period) names it in the legend too, beside a dashed swatch. That entry is a name, not a button: the comparison line follows the datasets on screen.
## Starting with datasets hidden
Set [`isInitiallyHidden: true`](https://lovelychart.io/guide/api.md#datasets-isInitiallyHidden) on a dataset to start it hidden, its button unchecked, so the reader can show it from the legend. It suits a dataset that's useful on demand but crowds the chart, such as a small series beside large ones:
```js
new LovelyChart(element, {
type: 'line',
labels,
datasets: [
{ name: 'Apples', values: apples },
{ name: 'Oranges', values: oranges },
{ name: 'Kiwi', values: kiwi, isInitiallyHidden: true },
],
});
```
A lone dataset that starts hidden keeps its legend, as the legend is the way to show it.
## Reacting to the legend
[`onHiddenSeriesChange`](https://lovelychart.io/guide/api.md#onHiddenSeriesChange) is called whenever the reader shows or hides a dataset in the legend, with the names and the indexes of the datasets now hidden:
```html
```
The datasets that `isInitiallyHidden` starts hidden go unreported, on creation and on `update()`, as the page knows them already.
Together, the two let the chart remember the reader's choice across visits:
```js
const hidden = JSON.parse(localStorage.getItem('fruit-hidden') ?? '[]');
new LovelyChart(element, {
...params,
datasets: params.datasets.map((dataset) => ({
...dataset,
isInitiallyHidden: hidden.includes(dataset.name),
})),
onHiddenSeriesChange: (names) => localStorage.setItem('fruit-hidden', JSON.stringify(names)),
});
```
Within one visit, `update()` resets the legend unless you pass [`shouldKeepFilter: true`](https://lovelychart.io/guide/api.md#shouldKeepFilter), which keeps the datasets the reader hid: see [Updating data](https://lovelychart.io/guide/updating.md).
## A legend elsewhere on the page
[`legendContainer`](https://lovelychart.io/guide/api.md#legendContainer) takes an element of the page that holds the legend in place of the end of the chart, as in a toolbar above it. The legend takes its spacing variables from that element and its ancestors, and, while `--lovely-chart-font-family` is unset, the font family of that element.
[`setLegendContainer(element)`](https://lovelychart.io/guide/api.md#setLegendContainer) moves the legend later, without a rebuild: its buttons keep the datasets they hide, and the chart its zoom, range and selection. `setLegendContainer(undefined)` moves it back to the end of the chart.
```html
Sales by region
```
The legend stays where `setLegendContainer()` put it through a zoom, a resize and an orientation change. `update()` places it by the `legendContainer` of its new data, so pass the element in every update that should keep it there.
## Hiding the legend
- A chart of a single dataset shows no legend, unless the dataset starts hidden or the chart has a `comparison`.
- A [sparkline](https://lovelychart.io/guide/api.md#isSparkline) has no legend.
- For a chart of several datasets, point `legendContainer` at an element the page never shows, such as one left out of the document. The legend goes there, out of sight, and the reader can no longer hide a dataset:
```js
new LovelyChart(card, {
...params,
// The legend goes to an element left out of the document
legendContainer: document.createElement('div'),
});
```
An element with the `hidden` attribute works the same way. To show the datasets' names elsewhere in the colours the chart gives them, see [`getDefaultColors()`](https://lovelychart.io/guide/api.md#getDefaultColors).
## Spacing and styling
These CSS variables space the legend and size its buttons. They apply from the chart's element, any ancestor of it or `.lovely-chart--container`, and for a legend in `legendContainer`, from that element and its ancestors:
| Variable | Sets | Default |
|---|---|---|
| [`--lovely-chart-legend-gap`](https://lovelychart.io/guide/css.md#--lovely-chart-legend-gap) | The space between the buttons, as the CSS `gap`: one length, or a row gap and a column gap | `8px 6px` |
| [`--lovely-chart-legend-padding-bottom`](https://lovelychart.io/guide/css.md#--lovely-chart-legend-padding-bottom) | The space under the last row; `0` ends the chart at the legend | `24px` |
| [`--lovely-chart-button-padding`](https://lovelychart.io/guide/css.md#--lovely-chart-button-padding) | The padding on every side of a button, which also places its check mark | `7px` |
| [`--lovely-chart-button-radius`](https://lovelychart.io/guide/css.md#--lovely-chart-button-radius) | The corner radius of a button | `18px` |
| [`--lovely-chart-button-font-size`](https://lovelychart.io/guide/css.md#--lovely-chart-button-font-size) | The font size of the buttons and of the comparison entry | The size around them, the chart's `13px` |
| [`--lovely-chart-inset`](https://lovelychart.io/guide/css.md#--lovely-chart-inset) | The side inset of the legend, the header and the minimap | `10px` |
```html
```
Each button takes its outline, its label and its checked fill from [`--lovely-chart-series-color`](https://lovelychart.io/guide/css.md#--lovely-chart-series-color), which the chart sets on it to the colour of its dataset in the skin on screen. A checked button keeps a white label while it reads clearly on the fill, and takes a dark one on a pale fill, such as the light green `#9ED448`. The buttons take the font of the chart's text: see [Theming](https://lovelychart.io/guide/theming.md).
## Dashed and dotted entries
A `line` or `step` dataset drawn with [`isDashed`](https://lovelychart.io/guide/api.md#datasets-isDashed) or [`isDotted`](https://lovelychart.io/guide/api.md#datasets-isDotted) shows the dashes or the dots on the outline of its button, and on its tooltip swatch, so datasets of one colour still tell apart:
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
new LovelyChart(document.getElementById('chart'), {
title: 'Sign-ups by platform',
type: 'line',
labels: days(30),
datasets: [
{ name: 'iOS', color: '#3497ED', values: series(30, { start: 820, seed: 31 }) },
{ name: 'Android', color: '#3497ED', values: series(30, { start: 640, seed: 32 }), isDashed: true },
{ name: 'Web', color: '#3497ED', values: series(30, { start: 410, seed: 33 }), isDotted: true },
],
isUtc: true,
});
```
The button of such a dataset carries a `data-dashed` or a `data-dotted` attribute. Datasets of other types ignore both options, in the legend too.
---
# Minimap and ranges
A long series reads best a window at a time. The minimap under the plot draws all of the data in miniature, with a window over the part the plot shows: drag the window to pan, or drag its edges to widen or narrow it. This page covers the minimap, the window a chart opens on, locked data, selecting a range on the plot itself, and following the range from your code.
## Adding the minimap
Set [`withMinimap: true`](https://lovelychart.io/guide/api.md#withMinimap):
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
new LovelyChart(document.getElementById('chart'), {
title: 'Daily active users',
type: 'line',
labels: days(365),
datasets: [
{
name: 'Mobile',
values: series(365, { start: 18000, trend: 0.002, volatility: 0.04, seasonality: 0.12, seed: 41 }),
},
{
name: 'Desktop',
values: series(365, { start: 11000, trend: 0.001, volatility: 0.04, seasonality: 0.18, seed: 42 }),
},
],
withMinimap: true,
isUtc: true,
});
```
- The window opens on the last 20% of the labels. Drag it across to pan, or drag one of the handles at its sides, its ears, to resize it. It can't get narrower than the two ears.
- As the window moves, the plot shows the labels under it, the [Y range](https://lovelychart.io/guide/axes.md#the-y-axis-range) fits their values, and the [header caption](https://lovelychart.io/guide/dates.md#the-header-caption) names their dates.
- The minimap draws the datasets the [legend](https://lovelychart.io/guide/legend.md) shows, and fades out the ones the reader hides.
## The opening window
[`minimapRange`](https://lovelychart.io/guide/api.md#minimapRange) sets the window the chart opens on, in one of three forms:
| Value | Opens on |
|---|---|
| `{ from, to }` | The labels from index `from` to index `to`, both included: `{ from: 0, to: 6 }` for the first week of daily labels |
| `[begin, end]` | That part of the axis, in fractions from 0 to 1: `[0.8, 1]` for the last 20% |
| `'full'` | Every label |
It defaults to `[0.8, 1]` with the minimap and to `'full'` without it.
`{ from, to }` counts labels, so it opens on whole days, weeks or months whatever the length of the data:
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
const labels = days(180);
new LovelyChart(document.getElementById('chart'), {
title: 'Orders',
type: 'bar',
labels,
datasets: [
{ name: 'Orders', color: '#F79E39', values: series(180, { start: 260, seasonality: 0.25, seed: 7 }) },
],
withMinimap: true,
// The last 30 days
minimapRange: { from: labels.length - 30, to: labels.length - 1 },
isUtc: true,
});
```
- `from` and `to` are rounded and clamped to the labels. A range of no labels, as one with `from` after `to`, takes the default.
- A `bar` or `step` chart opens on the columns of those labels. A `line` or `area` chart opens on their points with half an interval past either end, within the axis, so the end points stay off the edges of the plot. A pie or a donut sums those labels.
- `minimapRange` works without the minimap too, for a chart that shows part of its data. The reader then has no window to drag, but can still [pick a range on the plot](#selecting-a-range-on-the-plot) with `isRangeSelectable`, and double-click it to see every label.
See [`minimapRange`](https://lovelychart.io/guide/api.md#minimapRange) for every rule.
## Locking older data
[`limitDate`](https://lovelychart.io/guide/api.md#limitDate) locks the labels before a timestamp, as data the reader has no access to, such as the history beyond a free plan. The minimap covers them with a blurred mask, a dashed edge and a lock, and its window starts no earlier than the first label at or after `limitDate`, wherever the reader drags it. [`onLimitedRangeClick`](https://lovelychart.io/guide/api.md#onLimitedRangeClick) is called when the reader clicks the mask, to offer what it locks:
```html
```
- Without `onLimitedRangeClick`, the mask lets the pointer through.
- A `minimapRange` that starts before the first open label starts on it, keeping its width.
- `limitDate` needs the minimap. It's ignored when it falls at or before the first label, which locks nothing, or after the label before the last, which would leave the window a single label.
> [!WARNING]
> The locked labels are still in the data you give the chart, so anyone can read them from the page. Leave out of it whatever the reader must not see.
## Selecting a range on the plot
With [`isRangeSelectable: true`](https://lovelychart.io/guide/api.md#isRangeSelectable), a mouse can pick the range on the plot itself: press, drag across the labels to look at, and release. The chart draws a band in [`--range-selection-color`](https://lovelychart.io/guide/css.md#--range-selection-color) while you drag, then opens a window on the labels under it, through the transition of a minimap drag. A double click shows the whole range again.
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
new LovelyChart(document.getElementById('chart'), {
title: 'Website visits',
type: 'line',
labels: days(120),
datasets: [
{ name: 'Visits', values: series(120, { start: 3300, seasonality: 0.2, seed: 1 }) },
{ name: 'Sign-ups', values: series(120, { start: 900, seasonality: 0.2, seed: 2 }) },
],
// Drag across the plot to look closer, and double-click to see it all
isRangeSelectable: true,
isUtc: true,
});
```
- The window takes the labels whose point, or the centre of whose column, the band holds. A `line` or `area` chart takes two points at least, so a band over one point leaves the range as it was.
- With a minimap, its window follows the range, starting no earlier than `limitDate` allows and no narrower than its ears. Without one, as here, the plot takes the range alike.
- A press that moves less than 4px is a click, and Escape ends a drag with no change.
- On a chart that [zooms](https://lovelychart.io/guide/zoom.md) on a click, the click that ends a drag zooms into nothing, and a double click zooms rather than showing the whole range.
- A touch keeps selecting a label, as without the option.
- The option is ignored on pie and donut charts, while the chart is zoomed, and with `noTooltip`.
## Following the range
[`onRangeChange`](https://lovelychart.io/guide/api.md#onRangeChange) tells you which labels are on screen, as `{ from, to }`, inclusive indexes in `labels`. The chart calls it on its first paint and after each frame that moves the labels: through a drag of the minimap, the transition to a range selected on the plot, a zoom, an `update()` and a resize. Use it to sum up the window, or to move another view of the same data along:
```html
```
- The callback runs at most once a frame, but on every frame of a drag, so keep it light.
- It's called with `undefined` when no labels are on screen: on a pie or a donut, from the start of a [zoom into shares](https://lovelychart.io/guide/zoom.md#zooming-into-shares) until the zoom out, and as `destroy()` tears the chart down.
- While zoomed into [detail data](https://lovelychart.io/guide/zoom.md#loading-detail-data), the indexes count the labels of that data.
The range means what it means in `minimapRange`, so passing it back reopens the same window. Store the values of its labels rather than their indexes, which shift as new data arrives:
```js
const saved = JSON.parse(localStorage.getItem('orders-range') ?? 'null');
const from = saved ? labels.indexOf(saved.from) : -1;
const to = saved ? labels.indexOf(saved.to) : -1;
new LovelyChart(element, {
...params,
labels,
withMinimap: true,
minimapRange: from !== -1 && to !== -1 ? { from, to } : undefined,
onRangeChange: (range) => {
if (range) {
const ends = { from: labels[range.from], to: labels[range.to] };
localStorage.setItem('orders-range', JSON.stringify(ends));
}
},
});
```
`update()` opens its new data on the window of its own `minimapRange`, unless [`shouldKeepZoom: true`](https://lovelychart.io/guide/api.md#shouldKeepZoom) keeps the one the reader has while the labels stay the same: see [Updating data](https://lovelychart.io/guide/updating.md). To place an element of the page at a label as the window moves, pair `onRangeChange` with [`getLabelX()`](https://lovelychart.io/guide/api.md#getLabelX): see [Overlays](https://lovelychart.io/guide/overlays.md).
## Touch screens
- A swipe across the window drags it, and a swipe across an ear resizes it.
- A swipe up or down the window or an ear scrolls the page, and leaves the window where it was. The touch decides its way within its first 6px.
- Where the pointer is coarse, as on a phone, the ears take touches a little wider than they look.
- [Selecting a range on the plot](#selecting-a-range-on-the-plot) is for a mouse: a touch on the plot selects a label.
## Spacing
The minimap is 40px high. Two CSS variables place it:
- [`--lovely-chart-inset`](https://lovelychart.io/guide/css.md#--lovely-chart-inset), `10px` by default, insets it from the sides, as it does the header and the legend. The minimap canvas takes the width it leaves.
- [`--lovely-chart-minimap-margin-bottom`](https://lovelychart.io/guide/css.md#--lovely-chart-minimap-margin-bottom), `16px` by default, sets the space under it.
The colours of its mask and window come from the skin, as `--minimap-limit-color` gives the mask of `limitDate`: see [Theming](https://lovelychart.io/guide/theming.md).
---
# Zoom and drill-down
A chart can drill into a label: a click on a day opens the hours of that day, or the shares of its datasets in a pie. This page covers what a click does, loading detail data, zooming into shares, opening a chart zoomed, following the zoom from your code, and a zoom-out control of your own.
## What a click does
A chart zooms when it has somewhere to go:
- With [`onZoom`](https://lovelychart.io/guide/api.md#onZoom), it loads detail data for the label: see [Loading detail data](#loading-detail-data).
- A percentage chart, or one with `zoomToShares`, opens a pie or a donut of the label's shares: see [Zooming into shares](#zooming-into-shares).
Any other chart, or one with [`noZoom`](#turning-zoom-off), doesn't zoom: a click on its plot does nothing the hover doesn't. On a chart that zooms:
- A click on the plot zooms into the label under the pointer. On a touch screen, a tap selects a label, and a tap on its tooltip balloon zooms into it.
- The tooltip title ends with a chevron, a sign that the label opens. While the detail data loads, the balloon shows a spinner.
- The plot closes in on the label and opens on the zoomed view. The title in the header gives way to a zoom-out control, a magnifier and `Zoom out`, which returns to the overview, on the window it left.
- The zoom goes one level deep: the zoomed view zooms no further.
## Loading detail data
[`onZoom`](https://lovelychart.io/guide/api.md#onZoom) takes the value of the clicked label, its timestamp or the index of a text label, and returns a promise of the params of the zoomed view: its `type`, `labels`, `datasets` and the options it needs, the same shape the chart itself takes. If the promise rejects or resolves to `undefined`, the chart stays on its overview.
Here a click on a day loads its hours, kept in a JSON file per day:
```js
import LovelyChart from 'lovely-chart';
const data = await fetch('../data/bars.json').then((response) => response.json());
// The hours of a day are in zoom_bars/YYYY-MM/DD.json
async function fetchDay(timestamp) {
const date = new Date(timestamp);
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const response = await fetch(`../data/zoom_bars/${date.getFullYear()}-${month}/${day}.json`);
// A day with no file stays on the overview
return response.ok ? response.json() : undefined;
}
new LovelyChart(document.getElementById('chart'), {
...data,
title: 'Fruit sold',
onZoom: fetchDay,
});
```
Each file holds the hours of a week around its day, so the reader can pan to the days either side from the minimap.
### What the zoomed data sets
The zoomed view takes its options from the data `onZoom` returns, not from the chart: [`areLinesSmooth`](https://lovelychart.io/guide/api.md#areLinesSmooth), [`isYAxisOutward`](https://lovelychart.io/guide/api.md#isYAxisOutward), the [`isDashed`](https://lovelychart.io/guide/api.md#datasets-isDashed) of each dataset, the value formatting, [`hatchedRanges`](https://lovelychart.io/guide/api.md#hatchedRanges), [`eventLines`](https://lovelychart.io/guide/api.md#eventLines) and so on. Repeat the ones it shares with the chart:
```js
const shared = { valuePrefix: '$', isYAxisOutward: true, areLinesSmooth: true };
new LovelyChart(element, {
...overview,
...shared,
onZoom: async (timestamp) => ({ ...(await loadHours(timestamp)), ...shared }),
});
```
A few things stay the chart's while it's zoomed:
- The header: its title and zoom-out control, and whether it shows a caption. A chart with [`noCaption`](https://lovelychart.io/guide/api.md#noCaption) or text labels shows none while zoomed either, with no `noCaption` needed in the zoomed data.
- [`axisTextColor`](https://lovelychart.io/guide/api.md#axisTextColor), [`backgroundColor`](https://lovelychart.io/guide/api.md#backgroundColor), [`colorScheme`](https://lovelychart.io/guide/api.md#colorScheme) and [`ariaLabel`](https://lovelychart.io/guide/api.md#ariaLabel).
- The `on…` callbacks. [`onTooltipChange`](https://lovelychart.io/guide/api.md#onTooltipChange) and [`onRangeChange`](https://lovelychart.io/guide/api.md#onRangeChange) go on reporting, with the indexes of the zoomed view's labels from its first frame.
The zoomed datasets take their own colours: by key in [`colors`](https://lovelychart.io/guide/api.md#colors), `y0` for the first, `y1` for the second and so on, or from each dataset's `color`. A dataset with neither keeps the colour of the chart's dataset at its place, and one past the chart's datasets takes a default colour.
### The zoomed window
- The zoomed view opens on the clicked day: the labels from the clicked label's timestamp to a day later, when its labels hold that timestamp. A [`minimapRange`](https://lovelychart.io/guide/minimap.md#the-opening-window) in the zoomed data, counting its own labels, opens it on another window.
- Data with as many datasets as the chart keeps the minimap, which shows the zoomed data and moves its window in steps of the width it opened on, a day for the clicked day. The legend keeps the datasets the reader hid.
- Data with another number of datasets shows in full, without the minimap, with a legend of its own datasets.
## Zooming into shares
Without `onZoom`, a chart can open a pie or a donut of the shares its datasets have at the clicked label, with no data to load:
- A percentage chart does it by itself.
- [`zoomToShares: true`](https://lovelychart.io/guide/api.md#zoomToShares) opts any other chart in, as a stacked chart of absolute values, which would lose the values the overview is for if you made it a percentage chart. It's ignored when `onZoom` is given.
- [`zoomType`](https://lovelychart.io/guide/api.md#zoomType) picks `'pie'`, the default, or `'donut'`.
- [`circleLabelsAround`](https://lovelychart.io/guide/api.md#circleLabelsAround) sets how many labels either side of the clicked one the zoomed chart covers, `3` by default, which suits daily data. With the minimap, the window opens on the clicked label and the reader can drag it across those labels, the pie summing the ones in the window. `0` drills into the clicked label alone.
```js
import LovelyChart from 'lovely-chart';
import { months, series } from './demo-data.js';
new LovelyChart(document.getElementById('chart'), {
title: 'Support tickets by channel',
type: 'bar',
isStacked: true,
labels: months(12),
datasets: [
{ name: 'Email', values: series(12, { start: 820, seed: 2 }) },
{ name: 'Chat', values: series(12, { start: 640, trend: 0.03, seed: 5 }) },
{ name: 'Phone', values: series(12, { start: 310, trend: -0.02, seed: 9 }) },
],
withMinimap: true,
minimapRange: 'full',
zoomToShares: true,
zoomType: 'donut',
// Any month reaches the whole year in the zoomed minimap
circleLabelsAround: 11,
});
```
The pie or donut lists the sector under the pointer in its tooltip, and [`withGradient`](https://lovelychart.io/guide/api.md#withGradient) shades its sectors. A dataset drawn as [another type](https://lovelychart.io/guide/api.md#datasets-type) than the chart's, such as a line over the bars, takes no share.
## Opening zoomed
[`initialZoom`](https://lovelychart.io/guide/api.md#initialZoom) opens the chart already zoomed into a label, a label index or `'last'`, with no overview shown first and no transition. It works for shares and for `onZoom` alike, and the zoom out behaves as usual:
```js
import LovelyChart from 'lovely-chart';
const data = await fetch('../data/bars-monthly.json').then((response) => response.json());
new LovelyChart(document.getElementById('chart'), {
...data,
title: 'Monthly spending',
initialZoom: 'last',
zoomOutLabel: 'All months',
});
```
`initialZoom` is ignored on a chart that doesn't zoom, and an index outside the labels is clamped to them. This data zooms into a donut of the month, as its `zoomToShares` and `zoomType` say.
## Following the zoom
[`onZoomChange`](https://lovelychart.io/guide/api.md#onZoomChange) is called once a zoom settles, with the value of the label, its timestamp or the index of a text label, and its index in `labels`. Once the chart is zoomed out, it's called with `undefined` for both. Paired with `initialZoom`, it keeps the zoom in the page's address:
```js
const url = new URL(location.href);
const day = url.searchParams.get('day');
new LovelyChart(element, {
...params,
onZoom: loadHours,
initialZoom: day === null ? undefined : Number(day),
onZoomChange: (labelValue, labelIndex) => {
if (labelIndex === undefined) {
url.searchParams.delete('day');
} else {
url.searchParams.set('day', String(labelIndex));
}
history.replaceState(null, '', url);
},
});
```
> [!NOTE]
> `update()`, a resize of the window and an orientation change rebuild the chart on its overview, and `onZoomChange` reports the zoom out. [`update()` with `shouldKeepZoom: true`](https://lovelychart.io/guide/api.md#shouldKeepZoom) keeps the zoom while the labels stay the same, calling `onZoom` again: see [Updating data](https://lovelychart.io/guide/updating.md).
## Your own zoom-out control
For a page that draws its own header or back button, [`noZoomOutControl: true`](https://lovelychart.io/guide/api.md#noZoomOutControl) leaves out the chart's control, and the header keeps its title while zoomed. Call [`zoomOut()`](https://lovelychart.io/guide/api.md#zoomOut) from your control, and show the control while `onZoomChange` reports a zoom:
```html
Pick a month to see where the money went
```
`zoomOut()` starts on the next frame, and only if the chart is zoomed in then: from the moment `onZoomChange` reports a zoom until a zoom out starts. At any other time, it does nothing.
To keep the chart's control and change its words, set [`zoomOutLabel`](https://lovelychart.io/guide/api.md#zoomOutLabel), `'Zoom out'` by default. With [`noHeader`](https://lovelychart.io/guide/api.md#noHeader), or a header with nothing to show, the control floats over the plot while zoomed, at its top left, or its top right on a right-to-left page: see [Layout](https://lovelychart.io/guide/layout.md).
## Turning zoom off
[`noZoom: true`](https://lovelychart.io/guide/api.md#noZoom) turns zooming off, even on a percentage chart or one with `onZoom`, so a click only selects a label:
```js
new LovelyChart(element, {
type: 'area',
isPercentage: true,
labels,
datasets,
// A share chart that stays a share chart
noZoom: true,
});
```
---
# Annotations
Annotations are marks the chart draws on the canvas together with your data: horizontal rules at values, hatched runs of labels, vertical rules at moments, and a dashed line for a previous period. They move with the data through every pan, resize and skin change, with no code of your own.
## Which one to use
| Option | Draws | Use it for |
|---|---|---|
| [`referenceLines`](https://lovelychart.io/guide/api.md#referenceLines) | Dashed horizontal rules at values of the Y axis | Targets, limits, thresholds, pinning the Y range |
| [`hatchedRanges`](https://lovelychart.io/guide/api.md#hatchedRanges) | Diagonal hatching over a run of labels | Forecasts, estimates, periods still filling up |
| [`eventLines`](https://lovelychart.io/guide/api.md#eventLines) | Vertical rules, optionally with a pin head | Launches, outages, a change in how data is collected |
| [`comparison`](https://lovelychart.io/guide/api.md#comparison) | A dashed line of a previous period | "This month against last month", with the change in the tooltip |
All four are ignored on pie and donut charts. When you need something the canvas can't draw, such as a link or a button at a label, see [Overlays and custom marks](https://lovelychart.io/guide/overlays.md).
## Reference lines
A reference line is a dashed rule across the plot at a fixed value of the main Y axis. Each entry takes a `value`, an optional `label` drawn above the right end of the line, and an optional `color`, which defaults to the colour of the Y-axis labels.
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
new LovelyChart(document.getElementById('chart'), {
title: 'API latency, p95',
type: 'line',
labels: days(30),
datasets: [
{ name: 'p95', color: '#3497ED', values: series(30, { start: 180, volatility: 0.06, seed: 11 }) },
],
valueSuffix: ' ms',
referenceLines: [
// Above every value: the Y range stretches to show it
{ value: 250, label: 'SLO · 250 ms', color: { light: '#E65850', dark: '#F07068' } },
{ value: 200, label: 'Alert' },
],
isUtc: true,
});
```
The Y range always reaches every reference value, stacked charts included. That's why the 250 ms line above shows even though no value reaches it: a target never falls off the top of the plot.
### Pinning the Y range
Because the range always reaches each value, a line you can't see is a handy way to fix one end of the axis. Give it `color: 'transparent'` and it draws nothing:
```js
new LovelyChart(element, {
type: 'bar',
labels,
datasets: [{ name: 'Kiwi', values }],
// Starts the bars at zero, however close together their values are
referenceLines: [{ value: 0, color: 'transparent' }],
});
```
Pin the top the same way, as `{ value: 100, color: 'transparent' }` for a score out of 100 that should never look full at 80.
### Percentage charts
On a chart with `isPercentage`, `value` is a percentage from 0 to 100, and the range stays 0–100%:
```js
new LovelyChart(element, {
type: 'area',
isPercentage: true,
labels,
datasets,
// Half of the total, whatever the values
referenceLines: [{ value: 50, label: 'Half' }],
});
```
> [!NOTE]
> A `label` reads in the direction of the page, so on a right-to-left page a sign before a number moves after it. Wrap the number in U+2066 and U+2069, as `'\u2066-1.2K\u2069'`, to keep its sign first.
See [`referenceLines`](https://lovelychart.io/guide/api.md#referenceLines) for every rule.
## Hatched ranges
A hatched range marks a run of labels whose values aren't plain actuals: a forecast, an estimate, a partial count. `from` and `to` are inclusive label indexes, and the hatch shows on the plot and on the minimap.
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
const actualDays = 28;
const forecastDays = 7;
const values = series(actualDays + forecastDays, { start: 1200, trend: 0.004, seasonality: 0.12, seed: 3 });
new LovelyChart(document.getElementById('chart'), {
title: 'Orders',
type: 'line',
labels: days(actualDays + forecastDays),
datasets: [{ name: 'Orders', color: '#3497ED', values }],
hatchedRanges: [{
from: actualDays,
to: actualDays + forecastDays - 1,
label: 'Forecast',
hasEdge: true,
color: { light: '#108BE3', dark: '#48AAF0' },
note: 'Forecast from the trend of the last 4 weeks',
}],
isUtc: true,
});
```
Where the hatch starts and ends depends on the chart type:
- A `bar` or `step` chart hatches the columns of the range.
- A `line` or `area` chart starts the hatch at the point *before* the range, since the segment leading into an estimated value is estimated too, and ends it halfway to the label after the range.
### Labels and edges
- `label` is drawn at the bottom left of the hatch, in the axis font size. It keeps clear of the Y-axis labels and of the next range's label, and is dropped where it has no room.
- `hasEdge` draws a dashed rule where the hatch starts, as the line between actuals and a forecast. A range that starts at the first label gets no edge.
- `color` sets the hatch, the edge and the label together, and defaults to the colour of the Y-axis labels.
Ranges of one colour that touch hatch as one band, while each keeps its own label and edge.
### Periods still filling up
For the current day or month, whose value is still growing, set `isAccruing`. A `line` or `area` chart then starts the hatch halfway from the point before, rather than at it:
```js
import LovelyChart from 'lovely-chart';
import { months, series } from './demo-data.js';
const values = series(12, { start: 52000, trend: 0.02, volatility: 0.05, seed: 8 });
// The month in progress holds the revenue so far
values[11] = Math.round(values[11] * 0.55);
new LovelyChart(document.getElementById('chart'), {
title: 'Monthly revenue',
type: 'area',
labels: months(12),
datasets: [{ name: 'Revenue', color: '#5FB641', values }],
areaOpacity: 0.3,
valuePrefix: '$',
hatchedRanges: [{
from: 11,
to: 11,
isAccruing: true,
titleNote: 'month to date',
note: 'The month is still in progress',
}],
});
```
### Notes in the tooltip
A range can explain itself in the tooltip at each of its labels:
- `note` adds a line under the tooltip rows. A `\n` splits it into several lines.
- `titleNote` stands beside the tooltip title, as "month to date" above.
The notes of the ranges come first, then the hints of [event lines](#event-lines), then the notes of [`resolveTooltipNotes`](https://lovelychart.io/guide/api.md#resolveTooltipNotes); a line shown already is left out. Only one `titleNote` shows: the one of `resolveTooltipNotes` wins over a range's, and among ranges the first wins. See [Notes](https://lovelychart.io/guide/tooltip.md#notes) in the tooltip guide for more.
> [!NOTE]
> The minimap draws the hatch alone, without labels or edges, and a sparkline draws the hatch and the edges. Data that [`onZoom`](https://lovelychart.io/guide/api.md#onZoom) returns sets ranges of its own.
See [`hatchedRanges`](https://lovelychart.io/guide/api.md#hatchedRanges) for every rule.
## Event lines
An event line is a vertical rule at a moment of your labels: a launch, an outage, a change in how the data is collected. It runs from the bottom of the Y range up through the room above it, and can carry a label, a pin head and a note in the tooltip.
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
const launchIndex = 9;
const outageIndex = 21;
const signups = series(30, { start: 420, volatility: 0.12, seed: 7 }).map((value, i) => (
Math.round(value * (i >= launchIndex ? 1.4 : 1) * (i === outageIndex ? 0.6 : 1))
));
new LovelyChart(document.getElementById('chart'), {
title: 'Sign-ups',
type: 'bar',
labels: days(30),
datasets: [{ name: 'Sign-ups', color: '#5FB641', values: signups }],
eventLines: [
// At the start of the day's column: the launch went out at midnight
{ labelIndex: launchIndex, offset: 0, label: 'Launch' },
{
labelIndex: outageIndex,
label: 'Outage',
color: { light: '#E65850', dark: '#F07068' },
isDashed: true,
withHead: true,
hint: 'Sign-ups were down for 40 minutes',
},
],
isUtc: true,
});
```
### Placing the rule with `offset`
`labelIndex` picks the label, and `offset`, from 0 to 1, places the rule that far through the label's interval, so an event at noon can stand halfway between two daily points:
| Chart | `offset: 0` | Default | `offset: 1` |
|---|---|---|---|
| `line`, `area` | At the label's point | `0`, the point | At the next point |
| `bar`, `step`, or with bars or steps among its datasets | Start of the column | `0.5`, the centre | End of the column |
The last point of a `line` or `area` chart has no next point, so its rule stays at the point whatever the offset.
### Rules and pins
- A rule is a solid 1px line. `isDashed` draws it in 6px dashes 4px apart and `isDotted` in 2px dots 3px apart, as the dashes and dots of [`datasets[*].isDashed`](https://lovelychart.io/guide/api.md#datasets-isDashed) and [`datasets[*].isDotted`](https://lovelychart.io/guide/api.md#datasets-isDotted) are.
- `withHead` turns the rule into a pin: a disc of its colour, 8px across and ringed in the background colour, at the top of the canvas, over the data and the axis labels.
- `color` sets the rule, the head and the label, and defaults to the colour of the Y-axis labels.
### Labels and hints
- `label` reads bottom to top from the top of the rule, or from under its head, in the axis font size. It stands before the rule, or after it where it would cover the Y-axis labels or leave the plot. It's dropped where it fits on neither side, runs longer than its rule, or where the label of a later rule crowds it, so keep labels short.
- `hint` is a note under the tooltip rows at the rule's label, after the notes of hatched ranges and before those of `resolveTooltipNotes`.
> [!NOTE]
> A sparkline draws the rules and their heads without labels, and the minimap draws no event lines. Data that [`onZoom`](https://lovelychart.io/guide/api.md#onZoom) returns sets rules and hints of its own.
See [`eventLines`](https://lovelychart.io/guide/api.md#eventLines) for every rule.
## Comparison with a previous period
`comparison` draws a previous period as a dashed line beside your data, and the tooltip lists it first, with the change of the current total in percent.
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
// Eight weeks of orders: the last four on screen, the four before as the previous period
const orders = series(56, { start: 1000, trend: 0.005, seasonality: 0.12, seed: 5 });
new LovelyChart(document.getElementById('chart'), {
title: 'Orders',
type: 'line',
labels: days(28),
datasets: [{ name: 'Orders', color: '#3497ED', values: orders.slice(28) }],
comparison: { name: 'Previous 4 weeks', values: [orders.slice(0, 28)] },
isUtc: true,
});
```
`comparison` takes three fields:
- `name`, shown in the legend beside a dashed swatch and in the tooltip.
- `values`, the previous values **per dataset**, in the order of `datasets`, each aligned with `labels`. A `null` leaves a gap.
- `color`, which defaults to [`DEFAULT_COMPARISON_COLOR`](https://lovelychart.io/guide/api.md#DEFAULT_COMPARISON_COLOR), `#6B7280`.
The line draws the sum of the previous values of the datasets on screen, so on a stacked chart it follows the total as the reader hides and shows datasets in the legend:
```js
new LovelyChart(element, {
type: 'area',
isStacked: true,
labels: labels.slice(-56),
datasets: datasets.map((dataset) => ({ ...dataset, values: dataset.values.slice(-56) })),
comparison: {
name: 'Week before',
// Each dataset's values shifted back by a week
values: datasets.map(({ values }) => values.slice(-63, -7)),
},
});
```
In the tooltip, the comparison row is muted, and its change is bold and tinted by `--tooltip-change-positive` or `--tooltip-change-negative`; see [Styling](https://lovelychart.io/guide/tooltip.md#styling) in the tooltip guide. To show the change elsewhere on your page, read `comparison` from [`onTooltipChange`](https://lovelychart.io/guide/interaction.md).
> [!NOTE]
> `comparison` is ignored on percentage, pie and donut charts. A dataset drawn as another type than the chart's, through [`datasets[*].type`](https://lovelychart.io/guide/api.md#datasets-type), stays out of it. On a `line` chart with `areLinesSmooth`, the comparison line curves like the datasets.
## How the layers stack
When you combine annotations, the chart paints them in a fixed order. From the bottom up:
1. Bars and area fills.
2. Hatches of `hatchedRanges`: over fills, where they still show, and under lines, so the lines stay clear.
3. Lines and steps.
4. The `comparison` line.
5. The mask over unfocused bars while one is hovered.
6. Labels of `hatchedRanges`.
7. `eventLines` and their labels.
8. `referenceLines` and their labels.
9. Axis labels.
10. Pin heads of `eventLines` with `withHead`.
The hover line, its dots and the tooltip balloon sit above all of these. Here everything together:
```js
import LovelyChart from 'lovely-chart';
import { days, series } from './demo-data.js';
// Ten weeks of orders: five on screen, the last of them a forecast, and the five before as the previous period
const orders = series(70, { start: 1000, trend: 0.005, seasonality: 0.12, seed: 5 });
new LovelyChart(document.getElementById('chart'), {
title: 'Orders',
type: 'line',
labels: days(35),
datasets: [{ name: 'Orders', color: '#3497ED', values: orders.slice(35) }],
comparison: { name: 'Previous 5 weeks', values: [orders.slice(0, 35)] },
referenceLines: [{ value: 1600, label: 'Target', color: { light: '#5FB641', dark: '#7BC862' } }],
hatchedRanges: [{ from: 28, to: 34, label: 'Forecast', hasEdge: true, note: 'Forecast' }],
eventLines: [{
labelIndex: 14,
label: 'Campaign',
isDotted: true,
withHead: true,
hint: 'Autumn campaign starts',
}],
isUtc: true,
});
```
Every `color` here takes any of the forms described in [Theming and colours](https://lovelychart.io/guide/theming.md). Reference lines, hatched ranges and event lines that leave `color` out take the colour of the Y-axis labels, so they follow [`axisTextColor`](https://lovelychart.io/guide/api.md#axisTextColor) when you set it.
---
# Updating data and loading
A chart holds one set of data at a time. `update()` swaps in the next one, `setLoading()` shows the chart as waiting for it, and `destroy()` tears the chart down when you're done.
## Replacing the data
Call [`update(newData, options?)`](https://lovelychart.io/guide/api.md#update) with an object of the same shape you passed to the constructor. The chart rebuilds from it on the spot:
```js
import LovelyChart from 'lovely-chart';
import { random } from './demo-data.js';
const STEP = 5 * 60 * 1000;
const nextRandom = random(4);
const nextValue = () => Math.round(300 + nextRandom() * 120);
let labels = Array.from({ length: 36 }, (_, i) => Date.UTC(2026, 9, 31, 9) + i * STEP);
let values = labels.map(nextValue);
const buildParams = () => ({
title: 'Requests per 5 minutes',
type: 'line',
labels,
datasets: [{ name: 'Requests', color: '#3497ED', values }],
});
const chart = new LovelyChart(document.getElementById('chart'), buildParams());
// Every 2 seconds a new point arrives and the oldest leaves
setInterval(() => {
labels = [...labels.slice(1), labels[labels.length - 1] + STEP];
values = [...values.slice(1), nextValue()];
chart.update(buildParams(), { shouldKeepSelection: true });
}, 2000);
```
`newData` replaces the old params entirely, so it must be complete: the `type`, the options and the callbacks too, not only the `labels` and `datasets`. Keeping the fixed part in one object and spreading it into each update keeps this short:
```js
const params = {
title: 'Orders',
type: 'line',
withMinimap: true,
onSelectedIndexChange: (index) => highlightRow(index),
};
const chart = new LovelyChart(element, { ...params, ...(await fetchOrders('2026-10')) });
// Later
chart.update({ ...params, ...(await fetchOrders('2026-11')) });
```
> [!WARNING]
> The chart keeps a reference to the object you pass, and builds from it again on a resize or an orientation change. If you change that object afterwards, the change shows from the next rebuild on. Always pass a new object for new data, as the examples here do, rather than editing the one the chart holds.
A call to `update()` after `destroy()` does nothing.
## What `update()` resets
By default, `update()` gives the reader a fresh view of the new data. It resets:
- the zoom, returning a zoomed chart to its overview;
- the window, of the minimap or of a range selected on the plot;
- the datasets the reader showed or hid in the legend;
- the selected label and its tooltip;
- a drag, a long press or a hover in progress.
The callbacks report what ends: [`onSelectedIndexChange`](https://lovelychart.io/guide/api.md#onSelectedIndexChange) and [`onTooltipChange`](https://lovelychart.io/guide/api.md#onTooltipChange) with `undefined` when a selection ends, and [`onZoomChange`](https://lovelychart.io/guide/api.md#onZoomChange) with `undefined` when a zoom ends. The new data's first frame then reports its labels through [`onRangeChange`](https://lovelychart.io/guide/api.md#onRangeChange).
## Keeping the reader's view
When the new data is a refresh of the same view, as new values for the same days, resetting would throw away what the reader was looking at. The second argument of `update()` keeps parts of it:
| Option | Keeps |
|---|---|
| [`shouldKeepFilter`](https://lovelychart.io/guide/api.md#shouldKeepFilter) | The datasets the reader showed or hid in the legend |
| [`shouldKeepZoom`](https://lovelychart.io/guide/api.md#shouldKeepZoom) | The window and the zoom, while the labels stay the same |
| [`shouldKeepSelection`](https://lovelychart.io/guide/api.md#shouldKeepSelection) | The selected label, while a label of the same value is in the window |
| [`isAnimated`](https://lovelychart.io/guide/api.md#isAnimated) | Not a part of the view: cross-fades into the new data |
Each one is `false` by default. Try them here: hide a dataset, drag the minimap, point at a day, then refresh.
```html
```
### Keeping hidden datasets
With `shouldKeepFilter`, each dataset of the new data starts shown or hidden as the matching one was. Datasets match by their place in `datasets`, or by `name` when the new data has another number of datasets. A dataset with no match, and every dataset when the match would hide them all, starts as its `isInitiallyHidden` says.
[`onHiddenSeriesChange`](https://lovelychart.io/guide/api.md#onHiddenSeriesChange) is called once the new data is built, if the hidden datasets differ from those before.
### Keeping the window and the zoom
With `shouldKeepZoom`, the window stays where the reader put it, whether they dragged the minimap or selected a range on the plot, **as long as the new data has the same `labels`**. With other labels, the window and the zoom reset as usual.
A zoomed chart opens zoomed into the same label, with no overview shown and no transition, calling [`onZoom`](https://lovelychart.io/guide/api.md#onZoom) again for it, and zooming out returns to the kept window. `onZoomChange` isn't called again for a zoom it already reported.
### Keeping the selection
With `shouldKeepSelection`, the selected label stays selected at the index of the label of the same value in the new data, as long as that label is in the window the chart opens on. That's what keeps the tooltip in place in the streaming example above, even as the labels shift by one.
- A selection by the keyboard or by [`selectLabel()`](https://lovelychart.io/guide/api.md#selectLabel) holds.
- A selection by pointer or touch still clears as usual, once the pointer leaves the chart or a touch lands elsewhere.
- The selection ends when its label is gone or outside the window, or when a zoom shows or is kept.
`onSelectedIndexChange` is called on the first frame of the new data only if the index changes, and `onTooltipChange` only if what the tooltip shows changes.
## Cross-fading
`isAnimated: true` cross-fades the old chart into the new one over 400ms. It suits a change of subject, such as another period or another region, where the reader benefits from seeing that something changed.
During the fade, the old chart, with its plot, axes, header, minimap and legend, stays in the new chart's place, under it:
- It takes no room in the layout, so the page lays out around the new chart at once. While the old chart is taller than the new one, it covers the content that follows.
- No pointer, focus or assistive technology reaches it.
- A legend in [`legendContainer`](https://lovelychart.io/guide/api.md#legendContainer) cross-fades in its place there.
Another `update()` with `isAnimated` fades the chart out from wherever its fade has reached. An `update()` without it, a resize, an orientation change or `destroy()` ends the fades at once.
> [!NOTE]
> When the reader's system asks for reduced motion (`prefers-reduced-motion: reduce`), `isAnimated` is ignored and the data swaps at once. See [Accessibility](https://lovelychart.io/guide/accessibility.md#motion).
## Loading states
A chart that fetches its data has two waits to cover: before the first data arrives, and while the next data loads over data already on screen. [`isLoading`](https://lovelychart.io/guide/api.md#isLoading) covers both, and the chart and its legend are `inert` while it's set: they take no pointer, focus or keyboard input and leave the accessibility tree.
### A skeleton before the first data
Pass `isLoading: true` with no labels, `labels: []`, and the chart draws a skeleton of itself in its own geometry: a block over the data area of the plot, the circle of a pie or the ring of a donut, the box of the minimap, and a pill for each legend entry. Give the datasets their names and empty `values`, and the pills take the size of the legend to come, so nothing jumps when the data arrives.
```html
```
The header keeps its title, and the band of a caption of dates, so the plot doesn't move either. The skeleton pulses, unless the reader prefers reduced motion.
### Dimming the data while the next loads
Over data already on screen, `isLoading` dims the plot, the minimap and the legend instead. To set it without rebuilding the chart, call [`setLoading()`](https://lovelychart.io/guide/api.md#setLoading):
```js
chart.setLoading(true);
const data = await fetchOrders(nextPeriod);
chart.update({ ...params, ...data });
```
`setLoading(true)` keeps the zoom, the range, the hidden datasets and the selected label as they are, and calls no callback. `setLoading(false)` shows the data in full again, for a load that fails or is cancelled. You rarely need it after a successful load: `update()` takes the loading state of its own params, so data without `isLoading` shows as loaded.
### Styling the skeleton
The skeleton takes the `--skeleton-color` custom property, a translucent tint by default. Set your own on `.lovely-chart--container`, one for each skin, as the example above does; see [Theming and colours](https://lovelychart.io/guide/theming.md#writing-a-skin-of-your-own) for the selectors. A legend in a [`legendContainer`](https://lovelychart.io/guide/api.md#legendContainer) of your own reads the property from that element or its ancestors, and takes a translucent grey while it's unset.
## A period switcher
Put together, these make the common pattern of a chart whose data comes from the network: a skeleton until the first response, then dimmed data and a cross-fade for each new period.
```html
```
A few things make this robust:
- **The skeleton names its datasets**, so the legend pills match the legend to come.
- **`setLoading(true)` before each request** dims the data on screen and makes the chart `inert`, so the reader can't select stale data while the new data loads.
- **The request counter** drops a response that arrives after a newer request, so a slow answer for "7 days" can't overwrite "90 days".
- **`shouldKeepFilter`** keeps the datasets the reader hid across periods. `shouldKeepZoom` would do nothing here, since each period brings labels of its own.
## Destroying a chart
Call [`destroy()`](https://lovelychart.io/guide/api.md#destroy) when the chart leaves the page, as when its view closes in a single-page app. It:
- removes the chart's elements from `element`, along with the `--lovely-chart-plot-area-*` and `--lovely-chart-plot-padding-top` variables it set there;
- calls [`onPlotAreaChange`](https://lovelychart.io/guide/api.md#onPlotAreaChange) with `undefined`, and [`onRangeChange`](https://lovelychart.io/guide/api.md#onRangeChange) with `undefined` if it last reported labels, so overlays of your page can hide;
- detaches every global listener, including the window's `resize` and the observer of the theme, and cancels pending animation frames and timeouts;
- calls back nothing after that.
`destroy()` is idempotent, and every other method does nothing after it. In a framework, call it from the cleanup of the component that created the chart, as in React's `useEffect`:
```js
useEffect(() => {
const chart = new LovelyChart(elementRef.current, params);
return () => chart.destroy();
}, [params]);
```
See [Frameworks](https://lovelychart.io/guide/frameworks.md) for more on charts in components.
---
# Events and external control
A chart talks to your page in both directions. Callbacks in its params tell you what the reader does, as selecting a day or hiding a dataset, and instance methods let your page drive the chart, as selecting a label from a list or zooming out from a button of your own.
## Callbacks
Callbacks are params like any other: pass them to the constructor, and again in every [`update()`](https://lovelychart.io/guide/api.md#update), since the new params replace the old ones whole.
| Callback | Called with | When |
|---|---|---|
| [`onSelectedIndexChange`](https://lovelychart.io/guide/api.md#onSelectedIndexChange) | `labelIndex`, or `undefined` | The selected label changes, by pointer, touch, keyboard or `selectLabel()`; `undefined` once nothing is selected |
| [`onTooltipChange`](https://lovelychart.io/guide/api.md#onTooltipChange) | `{ labelIndex, title, rows, total?, comparison? }`, or `undefined` | What the tooltip shows changes, as another label is selected or a dataset is shown or hidden; called after `onSelectedIndexChange` |
| [`onHiddenSeriesChange`](https://lovelychart.io/guide/api.md#onHiddenSeriesChange) | `names`, `datasetIndexes` of the hidden datasets | The reader shows or hides a dataset in the legend |
| [`onZoomChange`](https://lovelychart.io/guide/api.md#onZoomChange) | `labelValue`, `labelIndex`, or `undefined` for both | A zoom into a label settles, or the chart is back in its overview |
| [`onRangeChange`](https://lovelychart.io/guide/api.md#onRangeChange) | `{ from, to }` label indexes, or `undefined` | A frame draws the labels at a new x: the first paint, each frame of a minimap drag or of a zoom's transition, the first paint after `update()` or a resize |
| [`onPlotAreaChange`](https://lovelychart.io/guide/api.md#onPlotAreaChange) | `{ left, top, width, height }`, or `undefined` | The first paint, and each change of the data area of the plot |
| [`onLimitedRangeClick`](https://lovelychart.io/guide/api.md#onLimitedRangeClick) | nothing | The reader clicks the locked part of the minimap that [`limitDate`](https://lovelychart.io/guide/api.md#limitDate) masks |
| [`onZoom`](https://lovelychart.io/guide/api.md#onZoom) | `labelValue` | The chart zooms into a label and needs its data: return a `Promise` of the params of the zoomed chart |
Here is each callback reporting as you use the chart. Point at a month, hide a category, drag the minimap, or click a month to zoom into its shares:
```html
onSelectedIndexChange
—
onTooltipChange
—
onHiddenSeriesChange
—
onRangeChange
—
onZoomChange
—
```
A few things worth knowing:
- **Indexes, not values.** `onSelectedIndexChange`, `onTooltipChange` and `onRangeChange` give indexes in `labels`. Look the label up in your own data when you need its date.
- **`undefined` means "nothing".** The callbacks report the end of what they track with `undefined`: nothing selected, an empty tooltip, the overview after a zoom, no labels on screen, a destroyed chart.
- **What the reader starts with goes unreported.** `onHiddenSeriesChange` isn't called for the datasets that start hidden by `isInitiallyHidden`, on creation or on `update()`.
- **`onRangeChange` runs on every frame of a pan.** Keep it light, and don't call `update()` from it unconditionally: the first frame of the new data reports again, so the chart would rebuild on every frame.
### Remembering what the reader hid
`onHiddenSeriesChange` and [`isInitiallyHidden`](https://lovelychart.io/guide/api.md#datasets-isInitiallyHidden) together let a chart come back as the reader left it:
```js
const STORAGE_KEY = 'orders-chart-hidden';
const hiddenNames = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '[]');
new LovelyChart(element, {
...params,
datasets: params.datasets.map((dataset) => ({
...dataset,
isInitiallyHidden: hiddenNames.includes(dataset.name),
})),
onHiddenSeriesChange: (names) => localStorage.setItem(STORAGE_KEY, JSON.stringify(names)),
});
```
### Linking to a zoomed label
`onZoomChange` reports the index of the zoomed label, and [`initialZoom`](https://lovelychart.io/guide/api.md#initialZoom) opens a chart zoomed into one, so a URL can carry the zoom:
```js
const url = new URL(location.href);
const day = url.searchParams.get('day');
new LovelyChart(element, {
...params,
initialZoom: day === null ? undefined : Number(day),
onZoomChange: (labelValue, labelIndex) => {
if (labelIndex === undefined) {
url.searchParams.delete('day');
} else {
url.searchParams.set('day', String(labelIndex));
}
history.replaceState(null, '', url);
},
});
```
See [Zoom](https://lovelychart.io/guide/zoom.md) for zooming in depth.
## Driving the chart from the page
The instance that `new LovelyChart()` returns has methods for everything a page commonly needs to do to a chart. Each one does nothing after [`destroy()`](https://lovelychart.io/guide/api.md#destroy).
| Method | Does |
|---|---|
| [`selectLabel(labelIndex)`](https://lovelychart.io/guide/api.md#selectLabel) | Selects a label as hovering it would; `undefined` clears the selection |
| [`zoomOut()`](https://lovelychart.io/guide/api.md#zoomOut) | Zooms a zoomed chart out to its overview |
| [`setLegendContainer(element)`](https://lovelychart.io/guide/api.md#setLegendContainer) | Moves the legend into an element of the page, or back with `undefined` |
| [`refreshColors()`](https://lovelychart.io/guide/api.md#refreshColors) | Reads the `var()` colours of the params again; see [Theming and colours](https://lovelychart.io/guide/theming.md) |
| [`setLoading(isLoading)`](https://lovelychart.io/guide/api.md#setLoading) | Shows the data as loading, or as loaded; see [Updating data and loading](https://lovelychart.io/guide/updating.md) |
| [`getLabelX(labelIndex, offset?)`](https://lovelychart.io/guide/api.md#getLabelX) | The x of a label on the plot; see [Overlays and custom marks](https://lovelychart.io/guide/overlays.md) |
### Selecting a label
`selectLabel(labelIndex)` does what hovering the label would: it shows its tooltip, focuses its bar, and calls `onSelectedIndexChange` and `onTooltipChange`. Unlike a hover, the selection holds while the pointer moves elsewhere on the page, and follows its label as the window pans. The pointer takes it over as it enters the chart, and it clears once its label leaves the visible range.
`selectLabel(undefined)` clears the selection.
> [!WARNING]
> The chart ignores `selectLabel()` before its first paint, the frame after it's created or updated. To select a label right away, wait a frame:
>
> ```js
> const chart = new LovelyChart(element, params);
> requestAnimationFrame(() => chart.selectLabel(params.labels.length - 1));
> ```
>
> It's also ignored for an index outside the visible range, on pie and donut charts, and with `noTooltip`.
### A zoom-out control of your own
The chart shows a zoom-out control in its header while zoomed. To place your own instead, as in a toolbar of the page, set [`noZoomOutControl`](https://lovelychart.io/guide/api.md#noZoomOutControl) and call `zoomOut()`, using `onZoomChange` to know when to show the control:
```html
```
Click a month to zoom into its shares, then use the button. `zoomOut()` starts on the next frame, and only if the chart is zoomed in by then: from the moment `onZoomChange` reports a zoom until a zoom out starts.
### Moving the legend
`setLegendContainer(element)` moves the legend into an element of your page without rebuilding the chart: the buttons keep the datasets they hide, and the chart its zoom, range and selection. Pass `undefined` to move it back to the end of the chart. For example, into a sidebar on wide screens:
```js
const wideScreen = matchMedia('(min-width: 60rem)');
const placeLegend = () => chart.setLegendContainer(wideScreen.matches ? sidebar : undefined);
placeLegend();
wideScreen.addEventListener('change', placeLegend);
```
The legend stays there through a zoom, a resize and an orientation change. `update()` places it by the [`legendContainer`](https://lovelychart.io/guide/api.md#legendContainer) of its new params, so pass the element there too once you've moved it. See [A legend elsewhere on the page](https://lovelychart.io/guide/legend.md#a-legend-elsewhere-on-the-page) for more.
## Keyboard selection
With [`isKeyboardSelectable`](https://lovelychart.io/guide/api.md#isKeyboardSelectable), the plot joins the tab order of the page. Once it has the focus:
| Key | Selects |
|---|---|
| ← / → | The previous or the next label; with nothing selected, the last label |
| Home / End | The first or the last label of the visible range |
A key pressed with Alt, Ctrl or Meta is left to the browser, so shortcuts such as Alt + ← for "back" keep working. A selection by the keyboard holds, as one by `selectLabel()` does, and reports through the same callbacks as a hover.
The plot keeps the focus through `update()` and a resize. The option is ignored on pie and donut charts, and with `noTooltip`; the pie or donut a zoom opens leaves the tab order while it shows. See [Accessibility](https://lovelychart.io/guide/accessibility.md#keyboard) for what else the keyboard reaches.
## Selecting a range with the mouse
With [`isRangeSelectable`](https://lovelychart.io/guide/api.md#isRangeSelectable), a mouse can drag across the plot to narrow the window to a run of labels. A band in [`--range-selection-color`](https://lovelychart.io/guide/css.md#--range-selection-color) follows the drag, and the release moves the window onto the labels under it, as a drag of the minimap would. On a chart that doesn't zoom in on a click, a double click shows the whole range again. Escape cancels a drag, and a touch keeps selecting a label.
```js
new LovelyChart(element, { ...params, isRangeSelectable: true });
```
`onRangeChange` reports each frame of the transition. The option is ignored on pie and donut charts, while zoomed and with `noTooltip`. See [Selecting a range on the plot](https://lovelychart.io/guide/minimap.md#selecting-a-range-on-the-plot) for the details.
## Linking a chart with a list
A chart often sits beside a list or a table of the same data. Linking them both ways makes the pair easier to read:
- **List → chart:** each row calls `selectLabel()` on hover and focus.
- **Chart → list:** `onSelectedIndexChange` marks the row of the selected label.
- **Steps:** buttons step the selection from the last selected label, as the arrow keys do on the focused plot.
```html
```
The rows mark the selected day with `aria-current="date"`, which both styles the row and tells assistive technology which day the chart shows. `isUtc` makes the chart read its dates in UTC, as the list does, so both name the same day.
---
# Accessibility
A chart is a picture of data, and a picture needs help to reach every reader. This page covers what the chart does on its own for assistive technology, keyboards and reduced motion, and the few things your page adds to make a chart work for everyone.
## What the chart exposes
Out of the box, a chart gives assistive technology:
- **A named image for the plot.** The plot takes `role="img"` and an accessible name that sums up the data it shows, as "Line chart, 1 Nov 2025 — 5 Nov 2025: Desktop, Mobile": its type, the span of its labels and the names of its datasets.
- **Legend buttons.** Each dataset's legend entry has `role="button"` and `aria-pressed`, `true` while the dataset shows. The buttons are in the tab order and toggle with Enter and Space. The legend always keeps at least one dataset shown.
- **No role on the chart element.** Only the plot is an image, so the legend buttons beside it stay reachable rather than becoming part of the picture.
The name of the plot follows the data: a zoom in or out and `update()` name it from the data they bring, as "Pie chart, …" for a zoom into the shares of a label. Dates span the way the header's caption names a range, in your [`dateLocale`](https://lovelychart.io/guide/api.md#dateLocale), and text labels from the first to the last, as "Bar chart, Mon — Sun: Orders".
## Naming the plot
The summary tells a reader what the chart is, but not what it shows. When the point of the chart is a finding, say it with [`ariaLabel`](https://lovelychart.io/guide/api.md#ariaLabel):
```js
new LovelyChart(element, {
...params,
ariaLabel: 'Orders by channel, last 30 days: web orders up 12% on the 30 days before',
});
```
A name you give stays across a zoom, so write one that holds for the zoomed views too, or update it with the data. The summary is in English, so on a page in another language, give every chart an `ariaLabel` in that language.
An empty string, `ariaLabel: ''`, leaves the plot out of the accessibility tree with `aria-hidden`. Use it where the page already says what the plot shows: a sparkline beside the figure and the name of its row, or a chart followed by a table of the same numbers.
## Keyboard
Two parts of a chart take the keyboard:
- The **legend buttons**, reachable with Tab, which show and hide datasets with Enter or Space.
- The **plot**, with [`isKeyboardSelectable`](https://lovelychart.io/guide/api.md#isKeyboardSelectable). It joins the tab order, and ← and → step the selection label by label, while Home and End select the first and the last label on screen. The tooltip shows as on hover, and the plot keeps the focus through `update()` and a resize, which rebuild it. See [Keyboard selection](https://lovelychart.io/guide/interaction.md#keyboard-selection) for the details.
The rest takes a pointer. Zooming into a label takes a click or a tap, the minimap and [`isRangeSelectable`](https://lovelychart.io/guide/api.md#isRangeSelectable) take a drag, and the zoom-out control in the header is a plain element that takes clicks, not a focusable button. Where these matter to your readers, give them controls of the page:
- A zoom-out button of your own: set [`noZoomOutControl`](https://lovelychart.io/guide/api.md#noZoomOutControl) and call [`zoomOut()`](https://lovelychart.io/guide/api.md#zoomOut) from a `