# 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 `
    ``` ## Default colours Datasets with no `color` take the default colours in order. The package exports them, so an element of your page that shows the same series, such as a table beside the chart, can match: | Export | Is | |---|---| | [`DEFAULT_COLORS`](https://lovelychart.io/guide/api.md#DEFAULT_COLORS) | The eight default colours, in order, as a frozen array | | [`getDefaultColors(datasetCount)`](https://lovelychart.io/guide/api.md#getDefaultColors) | The colours a chart of `datasetCount` datasets gives them, one per dataset | | [`DEFAULT_COMPARISON_COLOR`](https://lovelychart.io/guide/api.md#DEFAULT_COMPARISON_COLOR) | The colour of a `comparison` line with no `color`, `#6B7280` | A chart of fewer than eight datasets doesn't take the first colours of `DEFAULT_COLORS`, but a subset whose hues stand apart, as `#3497ED` and `#9ED448` for two. So call `getDefaultColors()` with the number of datasets rather than slicing the array: ```html
    MethodLast 30 days
    ``` Where only some datasets have a `color`, those without take the colours of `getDefaultColors(datasets.length)` from the first, in their order: with a colour on the first of three datasets, the second takes the first default colour and the third the second. ## The skin's custom properties The parts of the chart built from HTML take their colours from custom properties set on `.lovely-chart--container`, one value for each skin: | Property | Colours | Day | Night | |---|---|---|---| | `--text-color` | The title and caption of the header, the text of the tooltip, the comparison entry of the legend | `#222222` | `#FFFFFF` | | `--background-color` | The backdrop of a zoom-out control that floats over the plot | `#FFFFFF` | `#242F3E` | | `--tooltip-background` | The tooltip balloon | `#FFFFFF` | `#1C2533` | | `--tooltip-muted-text-color` | The comparison row and the notes of the tooltip | 70% `--text-color`, 30% `--tooltip-background` | The same mix | | `--tooltip-separator-color` | The rules in the tooltip | `--grid-lines` | `--grid-lines` | | `--tooltip-border` | The border of the balloon | `none` | `none` | | `--tooltip-change-positive`, `--tooltip-change-negative` | A rise and a fall against the `comparison` | `#108BE3`, `#E65850` | `#48AAF0`, `#F07068` | | `--grid-lines` | The ring of a tooltip swatch, and the default of `--tooltip-separator-color` | `#182D3B` at 10% | `#FFFFFF` at 10% | | `--zoom-out-text` | The zoom-out control | `#108BE3` | `#48AAF0` | | `--minimap-mask` | The minimap outside its window | `#E2EEF9` at 60% | `#304259` at 60% | | `--minimap-slider` | The frame and ears of the minimap window | `#C0D1E1` | `#56626D` | | `--minimap-limit-color` | The edge and the lock of a [`limitDate`](https://lovelychart.io/guide/api.md#limitDate) mask | `#616770` | `#BFC0C2` | | `--skeleton-color` | The skeleton of a [loading](https://lovelychart.io/guide/updating.md#loading-states) chart | `#182D3B` at 10% | `#FFFFFF` at 10% | | `--range-selection-color` | The band of [`isRangeSelectable`](https://lovelychart.io/guide/api.md#isRangeSelectable) | `#108BE3` | `#48AAF0` | The canvas, which draws the data, the grid, the axis labels and the halos around labels, doesn't read these properties: it takes the skin's built-in colours, and your [`axisTextColor`](#backgroundcolor-and-axistextcolor) and [`backgroundColor`](#backgroundcolor-and-axistextcolor) over them. See [`--background-color`](https://lovelychart.io/guide/css.md#--background-color) in the CSS reference for the complete list. ## Writing a skin of your own A skin of your own sets these properties for the day and the night skin, under selectors that reach each chart in the right skin only. Scope them to a class of your page, `.sales` here, so they don't reach other charts: ```css /* Day */ .sales .lovely-chart--container { --text-color: #2D2A26; --tooltip-background: #FFFDF8; } /* Night, for the default colorScheme: 'htmlClassName' */ html.theme-dark .sales .lovely-chart--container:not(.lovely-chart--container-scheme-system) { --text-color: #F3E9DC; --tooltip-background: #352D27; } /* Night, for colorScheme: 'system' */ @media (prefers-color-scheme: dark) { .sales .lovely-chart--container.lovely-chart--container-scheme-system { --text-color: #F3E9DC; --tooltip-background: #352D27; } } ``` The `:not()` and the `.lovely-chart--container-scheme-system` class keep each night rule to the charts of its `colorScheme`, so a chart that follows the system isn't turned dark by the class on ``, nor the other way round. Leave out the rule of a scheme your page doesn't use. > [!TIP] > When your page already has tokens that switch with its theme, let the skin read them, and one rule with both selectors serves the day and the night skin alike, as the example below does. The skin covers the HTML parts. For the canvas, set two params to match: - [`backgroundColor`](https://lovelychart.io/guide/api.md#backgroundColor), the colour of your surface, which the chart paints inside the hover dots, in the mask over unfocused bars, as a ring around pin heads and as a halo around labels on the plot. Without it, those take the skin's own white or blue-grey, which shows as a fringe on a surface of another colour. - [`axisTextColor`](https://lovelychart.io/guide/api.md#axisTextColor), the colour of the axis labels, which reference lines, hatched ranges and event lines also take when they have no `color`. Here is a warm "paper" skin, all of it from the page's tokens: ```html
    ``` To restyle the balloon itself, its shadow, padding or radius, see [Tooltip](https://lovelychart.io/guide/tooltip.md) and the [`.lovely-chart--tooltip-balloon`](https://lovelychart.io/guide/css.md#lovely-chart--tooltip-balloon) class. ## `backgroundColor` and `axisTextColor` These two params take the colour forms above, and reach the parts of the chart the custom properties don't: | Param | Colours | Default | |---|---|---| | [`backgroundColor`](https://lovelychart.io/guide/api.md#backgroundColor) | Inside the hover dots, the mask over unfocused bars, the ring around pin heads, the halo around the Y-axis labels and the labels of reference lines, hatched ranges and event lines | The skin's background | | [`axisTextColor`](https://lovelychart.io/guide/api.md#axisTextColor) | The axis labels, and reference lines, hatched ranges and event lines with no `color` | The skin's axis text | Without `backgroundColor`, only the Y-axis labels of [`areLabelsContrast`](https://lovelychart.io/guide/api.md#areLabelsContrast) get a halo; with it, all of them do. ## Pie and donut gradients [`withGradient`](https://lovelychart.io/guide/api.md#withGradient) shades each sector of a pie or donut from 10% lighter at its inner edge, the centre of a pie, to 10% darker at its outer edge, in whatever colours the datasets have. It applies to the pie or donut a zoom into shares opens too: ```js import LovelyChart from 'lovely-chart'; const data = await fetch('../data/donut.json').then((response) => response.json()); new LovelyChart(document.getElementById('chart'), { ...data, title: 'Fruit sold', withGradient: true, }); ``` For colours that hold up for every reader, see [Accessibility](https://lovelychart.io/guide/accessibility.md#colour-and-contrast). --- # Layout, sizing and fonts A chart takes the width your layout gives its element and a height you choose for its plot. Around the plot, a header, a minimap and a legend take their spacing and type from CSS custom properties, so you can fit a chart into a card, a dashboard tile or a table cell without touching its internals. ## Width A chart fills the full width of the element you pass to the constructor. Size that element with your layout, a grid, a flex row or a `max-width`, and the chart follows: ```css .dashboard { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 22rem), 1fr)); gap: 24px; } ``` In a grid or a flex row, let the element shrink below the width of its content with `min-width: 0`, or `minmax(0, 1fr)` for its column, so a chart doesn't hold its column open at the width it was built at. The chart measures its element as it builds. When the width of the window changes, or the device turns, it builds again at its element's new width, shortly after the resize ends. A rebuild keeps the datasets the reader hid and the place of the legend, clears the selection, and returns a zoomed chart to its overview. > [!TIP] > A change of the element's width alone, as when a sidebar opens, stretches the chart until the next rebuild. To rebuild at once, watch the element and call [`update()`](https://lovelychart.io/guide/api.md#update) with the same params, keeping the reader's view: > > ```js > let lastWidth = element.clientWidth; > new ResizeObserver(() => { > if (element.clientWidth === lastWidth) return; > lastWidth = element.clientWidth; > chart.update(params, { shouldKeepFilter: true, shouldKeepZoom: true, shouldKeepSelection: true }); > }).observe(element); > ``` ## Height The height you set is the height of the plot, the canvas that holds the axes and the data. The header, the minimap and the legend add their own height around it. - [`plotHeight`](https://lovelychart.io/guide/api.md#plotHeight) sets it in px. The default is `320`. - The [`--lovely-chart-plot-height`](https://lovelychart.io/guide/css.md#--lovely-chart-plot-height) custom property, on the chart's element or an ancestor, takes precedence over `plotHeight`. It takes a unitless number of px, a `px` length or a `rem` length. The custom property lets a media query give a chart another height on a small screen: ```css .sales-chart { --lovely-chart-plot-height: 320; } @media (max-width: 40rem) { .sales-chart { --lovely-chart-plot-height: 200; } } ``` The chart reads the property as it builds, so a new value takes effect on the next rebuild, which a resize of the window brings anyway. ## The header Above the plot, the header holds the [`title`](https://lovelychart.io/guide/api.md#title) at its start and a caption at its end: the range of dates on screen, which follows the window as the reader pans. Charts of text labels show no caption. | You want | Set | |---|---| | A title without the dates | [`noCaption: true`](https://lovelychart.io/guide/api.md#noCaption) | | No header band at all, the plot at the top | [`noHeader: true`](https://lovelychart.io/guide/api.md#noHeader) | | Another text in the zoom-out control | [`zoomOutLabel`](https://lovelychart.io/guide/api.md#zoomOutLabel), `'Zoom out'` by default | A header with nothing to show, with no `title` and no caption because of `noCaption` or text labels, folds away, so the plot starts at the top of the chart. With `noHeader`, the band goes whatever it holds, and the axes and the legend stay. While a chart with no header band is zoomed, its zoom-out control floats over the top inline-start corner of the plot, on a backdrop of the skin's `--background-color`. Set [`noZoomOutControl`](https://lovelychart.io/guide/api.md#noZoomOutControl) to leave it out, and offer [a control of your own](https://lovelychart.io/guide/interaction.md#a-zoom-out-control-of-your-own). These custom properties size the band, read from the chart's element or an ancestor: | Property | Sets | Default | |---|---|---| | [`--lovely-chart-header-height`](https://lovelychart.io/guide/css.md#--lovely-chart-header-height) | Height of the header band, and line height of its title and caption | `30px` | | [`--lovely-chart-header-margin-top`](https://lovelychart.io/guide/css.md#--lovely-chart-header-margin-top) | Space above the header band | `0` | | [`--lovely-chart-plot-margin-top`](https://lovelychart.io/guide/css.md#--lovely-chart-plot-margin-top) | Space between the header band and the plot | `10px`; none on a sparkline | | [`--lovely-chart-empty-header-height`](https://lovelychart.io/guide/css.md#--lovely-chart-empty-header-height) | Height of a header with nothing to show | `0` | `--lovely-chart-empty-header-height` keeps a band where there's nothing to show. In a row of charts where only some have a title, it levels the plots: ```css .chart-row { /* As tall as a header that shows something */ --lovely-chart-empty-header-height: 30px; } ``` ## Spacing The header, the minimap and the legend share a side inset, and the legend buttons have their own padding, radius and font size. All of them are custom properties, which apply from the chart's element, any ancestor of it or `.lovely-chart--container`, so one rule can space every chart on a page: | Property | Sets | Default | |---|---|---| | [`--lovely-chart-inset`](https://lovelychart.io/guide/css.md#--lovely-chart-inset) | Side inset of the header, the minimap and the legend | `10px` | | [`--lovely-chart-minimap-margin-bottom`](https://lovelychart.io/guide/css.md#--lovely-chart-minimap-margin-bottom) | Space under the minimap | `16px` | | [`--lovely-chart-legend-gap`](https://lovelychart.io/guide/css.md#--lovely-chart-legend-gap) | Space between legend entries, as the CSS `gap` | `8px 6px` | | [`--lovely-chart-legend-padding-bottom`](https://lovelychart.io/guide/css.md#--lovely-chart-legend-padding-bottom) | Space under the last row of the legend | `24px` | | [`--lovely-chart-button-padding`](https://lovelychart.io/guide/css.md#--lovely-chart-button-padding) | Padding on every side of a legend button | `7px` | | [`--lovely-chart-button-radius`](https://lovelychart.io/guide/css.md#--lovely-chart-button-radius) | Corner radius of a legend button | `18px` | | [`--lovely-chart-button-font-size`](https://lovelychart.io/guide/css.md#--lovely-chart-button-font-size) | Font size of the legend buttons | The chart's `13px` | In a card whose own padding insets its content, set the inset to `0`, and end the chart at its legend: ```html
    ``` > [!NOTE] > The plot keeps a gutter of its own, 10px, whatever the inset. With another inset, the header, the minimap and the legend move off the line of the Y-axis labels and the grid, as the 0 inset above shows. The chart sizes the minimap to the inset as it lays out: when it's built, on `update()`, and on a resize or an orientation change. A legend moved to a [`legendContainer`](https://lovelychart.io/guide/api.md#legendContainer) takes these properties from that element and its ancestors instead. ## Typography The chart's text, in the header, the legend, the tooltip and the labels the canvas draws, takes its family and weights from three custom properties, read from the chart's element or an ancestor: | Property | Sets | Default | |---|---|---| | [`--lovely-chart-font-family`](https://lovelychart.io/guide/css.md#--lovely-chart-font-family) | The family of all the chart's text | `'-apple-system', 'HelveticaNeue', Helvetica, Arial, sans-serif` | | [`--lovely-chart-font-weight`](https://lovelychart.io/guide/css.md#--lovely-chart-font-weight) | The regular weight: the legend, the names in the tooltip, the axis labels | `300` | | [`--lovely-chart-font-weight-bold`](https://lovelychart.io/guide/css.md#--lovely-chart-font-weight-bold) | The bold weight: the header, the tooltip title, the values and totals | `bold` | The size of the axis labels is the [`axisFontSize`](https://lovelychart.io/guide/api.md#axisFontSize) param, `10` px by default. The labels of hatched ranges and event lines take the same size. ```html
    ``` > [!WARNING] > `--lovely-chart-font-family: inherit` doesn't give the chart the font of your page: a custom property set to `inherit` takes the *custom property* of the parent, not its font. To use your page's font, set the property to its family list, or to a `var()` that holds it, as `--lovely-chart-font-family: var(--font-body)`. A web font that finishes loading after the chart is built reaches the canvas too: the chart draws its labels again in it, and measures again a column of [`isYAxisOutward`](https://lovelychart.io/guide/api.md#isYAxisOutward) labels. ## Sparklines and small multiples ### 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`, it fits a table cell beside the figure it shows: ```html
    MetricLast 30 daysToday
    ``` The bottom of a sparkline's Y range isn't rounded to an axis step. It sits at 0, unless the values go below 0 or their lowest is more than three quarters of their highest, so a sparkline of a figure that moves within a narrow band shows its movement rather than a flat line near the top. A sparkline still shows a tooltip on hover unless you set [`noTooltip`](https://lovelychart.io/guide/api.md#noTooltip). Of the [annotations](https://lovelychart.io/guide/annotations.md), it draws the hatches and edges of hatched ranges, and the rules and heads of event lines without their labels. ### Small multiples Small multiples, a grid of small charts of one kind, read best with one title and one key for all of them. Leave out what each chart would repeat: - [`noHeader`](https://lovelychart.io/guide/api.md#noHeader) leaves out the header band, while the axes stay. - [`noTooltip`](https://lovelychart.io/guide/api.md#noTooltip) leaves out the hover layer. - A [`legendContainer`](https://lovelychart.io/guide/api.md#legendContainer) that isn't in the document drops the legend: `legendContainer: document.createElement('div')`. - An [`ariaLabel`](https://lovelychart.io/guide/api.md#ariaLabel) names each chart, since the page's heading isn't part of it. ```html

    Last 4 weeks The 4 weeks before

    ``` Each cell gives the chart room with `minmax(0, 1fr)`, and `--lovely-chart-plot-margin-top` on the grid brings the plots closer to the headings of the page. --- # Overlays and custom marks Sometimes a mark belongs in the HTML of your page rather than on the canvas: a badge with a figure, an empty-state message, a link at the label of a release. The chart tells your page exactly where its plot is, through CSS custom properties and two callbacks, so such elements line up with the data and follow it through every update, resize and zoom. ## The plot-area variables From its first paint, the frame after it's created, the chart sets these custom properties on the `element` you passed to the constructor: | Variable | Holds | |---|---| | [`--lovely-chart-plot-area-left`](https://lovelychart.io/guide/css.md#--lovely-chart-plot-area-left) | Left edge of the data area, in px | | `--lovely-chart-plot-area-top` | Top edge of the data area, in px | | `--lovely-chart-plot-area-width` | Width of the data area, in px | | `--lovely-chart-plot-area-height` | Height of the data area, in px | | [`--lovely-chart-plot-padding-top`](https://lovelychart.io/guide/css.md#--lovely-chart-plot-padding-top) | The room above the data area, `15px`, or `2px` on a sparkline | The data area is where the data draws: from the start of the plot, after an [`isYAxisOutward`](https://lovelychart.io/guide/api.md#isYAxisOutward) column of labels, to its end, and from the top of the Y range down to the X-axis baseline. A pie or donut sets the square around its circle, and a sparkline its plot inset by 2px. The `--lovely-chart-plot-padding-top` room above it is where pin heads and the labels of [event lines](https://lovelychart.io/guide/annotations.md#event-lines) rise. The values are lengths from the inside of the element's border, so an absolutely positioned child of the element covers the data area with no arithmetic of its own: ```css .chart { position: relative; } .chart-overlay { position: absolute; left: var(--lovely-chart-plot-area-left); top: var(--lovely-chart-plot-area-top); width: var(--lovely-chart-plot-area-width); height: var(--lovely-chart-plot-area-height); /* Lets the pointer through to the tooltip */ pointer-events: none; } ``` ```js const element = document.querySelector('.chart'); new LovelyChart(element, params); const overlay = document.createElement('div'); overlay.className = 'chart-overlay'; element.appendChild(overlay); ``` The chart rewrites the variables whenever the area changes: on `update()`, a resize or an orientation change, a zoom into data of another label column or into a pie, a web font that changes the axis font, and a style of your page that moves the plot, as by folding the header. [`destroy()`](https://lovelychart.io/guide/api.md#destroy) removes them. > [!NOTE] > The variables describe one chart. Of several charts in one element, they describe the one that wrote them last, so give each chart with an overlay an element of its own. ### A badge in the corner of the plot Here a badge sums up the forecast week at the bottom left of the plot. It's positioned by the variables alone, so it stays in its corner at any width: ```html
    ``` The badge comes before the chart in the element, so the line and the tooltip paint over it; see [Stacking](#stacking) below. ## Following the plot area from script When you position something from JavaScript rather than CSS, as when you size a canvas or an SVG of your own to the plot, use [`onPlotAreaChange`](https://lovelychart.io/guide/api.md#onPlotAreaChange). The chart calls it with `{ left, top, width, height }` in px, the same numbers as the variables, whenever it writes them, and with `undefined` as `destroy()` removes them: ```js new LovelyChart(element, { ...params, onPlotAreaChange: (area) => { svg.style.display = area ? '' : 'none'; if (!area) return; Object.assign(svg.style, { left: `${area.left}px`, top: `${area.top}px` }); svg.setAttribute('width', area.width); svg.setAttribute('height', area.height); }, }); ``` A pan, or a zoom that leaves the area as it is, moves the labels across it without a call of `onPlotAreaChange`. For an element tied to a label, follow the labels instead, as the next section does. ## Placing an element at a label [`getLabelX(labelIndex, offset?)`](https://lovelychart.io/guide/api.md#getLabelX) returns the x of a label in px from the left of the plot area, where the last frame drew it: at its point on a `line` or `area` chart, and at the centre of its column on a `bar` or `step` chart. Add the area's `left` to place an element at it. Call it whenever the labels move, which [`onRangeChange`](https://lovelychart.io/guide/api.md#onRangeChange) reports frame by frame through a drag of the minimap and the transition of a zoom, and whenever the area changes. Here a link to the release notes stands above the day of a release, over a dashed [event line](https://lovelychart.io/guide/annotations.md#event-lines). Drag the minimap, and the link moves with the canvas and hides once its day leaves the window: ```html
    ``` `getLabelX()` returns `undefined` where the label has no x, which is the cue to hide the element: - for an index outside the visible range, the labels `onRangeChange` reports; - before the first frame of the chart, of `update()`, of a resize and of the data a zoom swaps in; - on pie and donut charts, and from the start of a zoom into shares; - after `destroy()`. A label at the edge of a panned window can map below 0 or past the area's width, since the window runs past the plot area; clip or hide the element there if it matters. `offset`, from 0 to 1, takes a point through the label's interval instead, as [`eventLines`](https://lovelychart.io/guide/annotations.md#event-lines) does: from the label's point to the next one on a `line` or `area` chart, and across its column on a `bar` or `step` chart, where `0` is its start and `0.5` its centre. ### While zoomed From the first frame of the data [`onZoom`](https://lovelychart.io/guide/api.md#onZoom) returns, `getLabelX()` maps that data's labels, not the overview's. If your element belongs to a label of the overview, hide it while zoomed, using [`onZoomChange`](https://lovelychart.io/guide/api.md#onZoomChange), which reports a zoom ahead of its first frame: ```js let isZoomedIn = false; const placeLink = () => { const x = plotArea && !isZoomedIn ? chart.getLabelX(releaseIndex) : undefined; link.hidden = x === undefined; if (x !== undefined) { link.style.left = `${plotArea.left + x}px`; } }; const chart = new LovelyChart(element, { ...params, onPlotAreaChange: (area) => { plotArea = area; placeLink(); }, onRangeChange: placeLink, onZoomChange: (labelValue) => { isZoomedIn = labelValue !== undefined; }, }); ``` ## Stacking The chart keeps its place among the children of `element` through updates and resizes, so the order you give your elements decides what paints over what: | Your element | Paints | |---|---| | Inserted before the chart | Under the plot and the hover line | | Added after the chart | Over the plot and the hover line, under the tooltip balloon | | Either, with a `z-index` above `1` | Over the tooltip balloon too | The tooltip balloon, and the zoom-out control where it floats over the plot, take `z-index: 1`. An element after the chart takes the pointer over its own box, so give a decorative one `pointer-events: none`, or the reader can't hover the data under it; one before the chart lies under the chart and gets no clicks where the chart covers it. While it holds a chart, `element` is a stacking context, with `isolation: isolate`. No `z-index` inside it reaches over the page around it, so a menu of your page placed inside `element` can't cover the content after the chart. Put such menus outside the element. > [!NOTE] > During the cross-fade of [`update()` with `isAnimated`](https://lovelychart.io/guide/updating.md#cross-fading), positioned elements after the chart in `element` paint over both the old and the new chart, and those before it under both. ## When to draw with the chart instead An overlay is the right tool for something interactive, as a link or a button, for rich HTML text, or for anything not tied to the data. For marks on the data itself, the chart's own [annotations](https://lovelychart.io/guide/annotations.md) are simpler and do more: | You want | Use | |---|---| | A band over a run of labels, as a forecast | [`hatchedRanges`](https://lovelychart.io/guide/api.md#hatchedRanges) | | A rule or a pin at a moment, with a label and a note in the tooltip | [`eventLines`](https://lovelychart.io/guide/api.md#eventLines) | | A line at a value, as a target | [`referenceLines`](https://lovelychart.io/guide/api.md#referenceLines) | They draw with the data, in the colours of the skin, show on the minimap and sparklines where it makes sense, and need no code to follow a pan or a zoom. --- # API reference Everything the package exports: the `LovelyChart` class with every option of a chart and every method, the default colours and the TypeScript types. The stylesheet has a reference of its own, [CSS variables and classes](https://lovelychart.io/guide/css.md). ```ts import LovelyChart, { DEFAULT_COLORS, DEFAULT_COMPARISON_COLOR, getDefaultColors, type LovelyChartParams, } from 'lovely-chart'; import 'lovely-chart/LovelyChart.css'; ``` ## Constructor ```ts new LovelyChart(element: HTMLElement, data: LovelyChartParams) ``` Builds a chart in `element` and paints it on the next frame. The chart takes the whole width of `element`, and builds again at its new width when the width of the window changes: see [Width](https://lovelychart.io/guide/layout.md#width). Argument | Type | Description | ---------|----|----| `element`| `HTMLElement` | DOM node in which the chart is rendered, taking its whole width. The chart sets the `--lovely-chart-plot-area-*` and `--lovely-chart-plot-padding-top` CSS variables on it; of several charts in one element, they describe the one that wrote them last. While it holds a chart, the chart's stylesheet makes it a stacking context: see [Placing elements over the plot](https://lovelychart.io/guide/overlays.md). `data`| [`LovelyChartParams`](#chart-options) | Parameters for a chart. ## Chart options Every parameter of the `data` object that `new LovelyChart(element, data)` and `update(newData)` take: the `LovelyChartParams` type. Only `type`, `labels` and `datasets` are required; every other parameter is optional, and a boolean one is `false` unless it says otherwise. ```ts import LovelyChart, { type LovelyChartParams } from 'lovely-chart'; const params: LovelyChartParams = { type: 'line', labels: [1735689600000, 1735776000000, 1735862400000], datasets: [{ name: 'Visitors', values: [1274, 1305, 1342] }], }; new LovelyChart(element, params); ``` The types the tables name, such as `ThemedColor` and `HatchedRange`, are exported by the package and listed under [Types](#types). ### Chart data The kind of chart, its labels and its datasets. See [Data format](https://lovelychart.io/guide/data.md) and [Chart types](https://lovelychart.io/guide/chart-types.md) for a walk-through. Parameter | Type | Description | ---------|----|----| `type`| `ChartType` | Chart type. Supported types: `line`, `area`, `bar`, `step`, `pie`, `donut` `labels`| `(number \| string)[]` | Array of UNIX timestamps in milliseconds, or arbitrary strings for text labels. A `pie` or `donut` of one total per dataset takes a single text label, as `labels: ['Total']`, each dataset's `values` holding its total: a text label shows no caption of dates, so the header holds the `title` alone, or folds with none. `datasets`| `LovelyChartDatasetParams[]` | Array of params for each dataset `datasets[*].name`| `string` | Dataset name `datasets[*].values`| `(number \| null)[]` | Array of dataset values; `null` leaves a gap `datasets[*].color`| `ThemedColor` | Dataset colour, in any of the forms under [Colours](#colours). The datasets with none take the [default colours](#default-colours) in order. `datasets[*].type`| `'line' \| 'bar' \| 'step'` | `line`, `bar` or `step` to draw the dataset as another type than the chart's `type`, as a line over bars; ignored on percentage, pie and donut charts. Lines and steps draw over bars and areas, whatever the order of `datasets`, and the hatch of `hatchedRanges` goes between them. A chart with a `bar` or `step` dataset gives every label a column, its lines running through the middles, and on hover masks the columns around the focused one, with a dot on each line. Bars that share the main Y axis with another type keep 0 on it, whichever side of it their values are. 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. Defaults to the chart's `type`. `datasets[*].isInitiallyHidden`| `boolean` | `true` to start the dataset hidden, its legend button unchecked. Default `false`. `datasets[*].isDashed`| `boolean` | `true` to draw a `line` or `step` dataset in 6px dashes 4px apart. Its legend button gets a dashed outline and a `data-dashed` attribute, and its tooltip swatch a dashed outline. Other types ignore it, legend included. Default `false`. `datasets[*].isDotted`| `boolean` | `true` to draw a `line` or `step` dataset in 2px dots 3px apart, whether or not it is `isDashed`. Its legend button gets a dotted outline and a `data-dotted` attribute, and its tooltip swatch a dotted outline. Other types ignore it, legend included. Default `false`. `isStacked`| `boolean` | `true` for values stacking on top of each other `isPercentage`| `boolean` | `true` for percentage based values `percentPrecision`| `number` | Digits after the point of the share a percentage chart's tooltip prints beside each value. Default `0`. ### Labels and dates How the X axis, the header caption and the tooltip title read the labels. See [Dates, time zones and locales](https://lovelychart.io/guide/dates.md). Parameter | Type | Description | ---------|----|----| `labelType`| `LabelType` | Optional X-axis label kind: `year`, `month`, `week`, `day`, `hour`, `5min`, `dayHour` or `text`. When omitted, it is inferred from the first two `labels` records: strings → `text`, timestamps → `year`/`month`/`week`/`day`/`hour`/`5min` depending on the step between them. `year` labels render as `2026`, `month` as `January`, `week` as `Week 1`, the ISO 8601 week number of the label's UTC date, so labels on 29 Dec 2025 and 28 Dec 2026 read `Week 1` and `Week 53`. Charts with `text` labels show no header caption. `labelFormatter`| `string` | Optional format of the X-axis labels of timestamps, over the one `labelType` gives: `statsFormatYear` (`2026`), `statsFormatMonth` (`January`), `statsFormatWeek` (`Week 1`), `statsFormat('day')` (`18 Nov`), `statsFormat('hour')` or `statsFormat('5min')` (`14:00`), or `statsFormatDayHour` (`18 Nov 14:00`). The tooltip title takes it too unless `tooltipFormatter` sets one, while the header caption keeps the granularity of `labelType`. The day, hour and day-hour formats follow the reader's time zone unless `isUtc` is set, while the year, month and week formats read UTC: with `isUtc: true` for labels at UTC midnight, `statsFormat('day')` labels weekly data by the date each week starts on, as `14 Sep` in place of `Week 38`, which a reader west of UTC would otherwise see as the day before. Defaults to the format of `labelType`. `tooltipFormatter`| `string` | Optional tooltip title format: `statsTooltipFormat('day')` (`18 Nov 2026`), `statsTooltipFormat('week')` (`Week of 16 Nov`), `statsTooltipFormat('hour')` or `statsTooltipFormat('5min')` (`14:00`), `statsFormatDayHourFull` (`18 Nov 14:00`). Defaults to the X-axis label. `isUtc`| `boolean` | `true` to read every date and time of the labels in UTC. Axis labels of days, hours and minutes and their tooltip titles otherwise follow the reader's time zone, while captions and day titles always read UTC. Default `false`. `dateLocale`| `DateLocale` | Optional localized date strings for axis, tooltip and caption labels: `{ months, monthsFull, weekDays, weekDaysShort, weekOf }`. Each array field is optional (12 months, or 7 weekdays starting Sunday) and falls back to English when omitted. `weekOf` is the words before the start date in a week title, `Week of` by default. The X-axis labels, text ones included, the header caption and 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. Without a letter, as in the caption `2022 — 2026` of a year chart, they read left to right, the way the X axis runs. ### Values and axes How the values read and where the Y axes stand. See [Axes and values](https://lovelychart.io/guide/axes.md). Parameter | Type | Description | ---------|----|----| `valuePrefix`| `string` | Optional string prepended to every formatted value (e.g. `$`) `valueSuffix`| `string` | Optional string appended to every formatted value `isCurrencyPrefix`| `boolean` | When `true`, a negative value is rendered with the minus sign in front of `valuePrefix` (`-$9.1` instead of `$-9.1`), and a negative label or tooltip total of `secondaryYAxis` with it in front of that scale's `prefix`. Use with currency-like prefixes. Default `false`. `hasSecondYAxis`| `boolean` | `true` to put the last dataset on a Y axis of its own, labelled at the right of the plot in the dataset's colour. The main Y axis is labelled in the colour of the first dataset, apart from a stacked or percentage chart's, whose labels keep 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, beside which it draws its own values; a percentage chart's tooltip prints no share on its row. `secondaryYAxis`| `SecondaryYAxisConfig` | Optional scale of the main Y axis in another unit: `{ label, multiplier, prefix?, suffix? }`. Each main Y-axis label times `multiplier`, between `prefix` and `suffix`, stands at the right of the plot, apart from a percentage chart's. The tooltip adds a row of `label` and its total times `multiplier`, formatted as the dataset values are, by `formatTooltipValue` when given, between `prefix` and `suffix`: under the Total row of a stacked or percentage `bar`, `step` or `area` chart, and under the dataset rows of any other chart or one with `isTooltipTotalInTitle`. `noFloatSteps`| `boolean` | `true` to step the main and the second Y axis in whole numbers, 1 at the finest, for counts: a range of 0 to 2 labels 0, 1 and 2. Default `false`. `isYAxisOutward`| `boolean` | `true` to put the main Y-axis labels in a column left of the plot, right-aligned, so the data never runs under them; the second Y axis keeps its labels inside the plot. The column fits the widest label the chart can show for its data in the axis font, `axisFontSize` included: over the whole value range of every dataset, hidden ones too, the reference lines and the previous period, below 0 as well, and at every step a window can take, down to a window of a single label. That can make it wider than any label a reader brings up at the narrowest window the minimap selects. It is measured once per data set, when the chart is built, on `update()` and on a zoom into or out of a day, so the plot holds still while the reader pans, animates or hides datasets, and again when a web font of the page changes the axis font, so the column fits a font that arrives after the chart: once the font finishes loading, or on the next frame the chart draws after the page adds a `FontFace` already loaded, which fires no event; the data `onZoom` returns sets `isYAxisOutward` of its own. A sparkline has no axes and no column. Default `false`. `areLabelsContrast`| `boolean` | `true` to draw each Y-axis label, of either axis, inside a halo of the background colour that keeps it legible over the data and the grid, 2px in from its side of the chart, which keeps the halo of a label inside the plot whole at the plot edge. An `isYAxisOutward` column grows by those 2px. Default `false`. `axisFontSize`| `number` | Font size of the axis labels in px, which take the family and the regular weight of the chart's text: see `--lovely-chart-font-family` and `--lovely-chart-font-weight`. Default `10`. `axisTextColor`| `ThemedColor` | Colour of the axis labels, in any of the forms under [Colours](#colours). ### Header and layout The parts of the chart around the plot and its size. See [Layout, sizing and fonts](https://lovelychart.io/guide/layout.md). Parameter | Type | Description | ---------|----|----| `title`| `string` | Chart headline `ariaLabel`| `string` | Accessible name of the plot, which takes `role="img"`. The chart element takes no role, so the legend buttons stay exposed to assistive technology. Defaults to an English summary of the data the plot shows: its type, the span of its labels and the names of its datasets, as `Line chart, 1 Nov 2025 — 5 Nov 2025: Desktop, Mobile`. Date labels span as the header caption names a range, in `dateLocale`, and text labels from the first to the last, as `Bar chart, Mon — Sun: Orders`. A zoom in or out and `update()` name the plot from the data they bring, as `Pie chart, …` for a zoom into the shares of a label, while a given `ariaLabel` stays across a zoom. An empty string leaves the plot out of the accessibility tree with `aria-hidden`, as for a sparkline whose row names it already. `plotHeight`| `number` | Height of the plot canvas in px. Default `320`. A `--lovely-chart-plot-height` custom property on the chart element or an ancestor takes precedence (a unitless number, `px` or `rem`), so a media query can set it. `noHeader`| `boolean` | `true` to leave out the band of the title and the caption, so the plot starts at the top of the chart, axes and legend kept. While zoomed, the zoom-out control floats over the top inline-start corner of the plot, as it does from a header with nothing to show (see `--lovely-chart-empty-header-height`), on a backdrop of `--background-color` that covers the top label of the main Y axis; `noZoomOutControl` leaves it out. Default `false`. `noCaption`| `boolean` | `true` to leave out the caption of the header, the dates on screen, also while zoomed: the data `onZoom` returns needs no `noCaption` of its own. With no `title`, the header has nothing to show and folds to `--lovely-chart-empty-header-height`. Default `false`. `isSparkline`| `boolean` | `true` to draw the datasets alone, inset by 2px: no axes, grid, header or legend. The bottom of the Y range stays unrounded to an axis step and follows the zero baseline of every chart: 0, unless the values go below 0 or their lowest is more than three quarters of their highest. Default `false`. `isLoading`| `boolean` | `true` to show the chart as loading, for a page that fetches its data. The chart element and its legend are `inert`: they take no pointer, focus or keyboard input and leave the accessibility tree. Data with labels dims on the plot, the minimap and the legend, as the data on screen does while the next data loads. Data with none, as `labels: []`, draws a skeleton of them in the chart's own geometry, so the chart its data builds takes the same place: a block over the data area of the plot, or the circle of a pie and the ring of a donut, the box of the minimap without its ruler, and a pill for each legend entry, sized by its name, so datasets with their names and empty `values` hold the place of the legend to come. The header keeps its title and the band of a caption of dates; for text labels and no `title`, `labelType: 'text'` folds it as the labels will. The skeleton takes `--skeleton-color`, and pulses unless the reader prefers reduced motion. `setLoading()` sets and clears it in place, keeping the zoom, the range, the hidden datasets and the selected label of the data on screen, and `update()` takes it from its params. Default `false`. `onPlotAreaChange`| `(area: { left, top, width, height } \| undefined) => void` | Optional function called with the plot area, `{ left, top, width, height }` in px from the inside of the border of `element`, whenever the chart writes the `--lovely-chart-plot-area-*` variables: on its first paint and at each change their row under "CSS variables" lists, and with `undefined` as `destroy()` removes the variables. A pan or a zoom moves the labels under an area it leaves as it is, as `onRangeChange` reports. ### Legend See [Legend](https://lovelychart.io/guide/legend.md). Parameter | Type | Description | ---------|----|----| `legendContainer`| `HTMLElement` | Element that holds the legend, in place of the chart container; `setLegendContainer()` moves the legend later. The legend takes its [spacing variables](https://lovelychart.io/guide/css.md#spacing-the-chart) from this element and its ancestors. The legend takes its spacing along, so an element the page never shows, such as one with the `hidden` attribute or one left out of the document, drops the legend from the chart. `onHiddenSeriesChange`| `(names: string[], datasetIndexes: number[]) => void` | Optional function called when the reader shows or hides a dataset in the legend, with the names and the indexes of the hidden datasets. The datasets the data starts hidden by `isInitiallyHidden` go unreported, on creation and on `update()`; `update()` with `shouldKeepFilter` reports the hidden datasets when they differ from those before. ### Style See [Theming and colours](https://lovelychart.io/guide/theming.md). Parameter | Type | Description | ---------|----|----| `colorScheme`| `'htmlClassName' \| 'system'` | `'htmlClassName'` follows the `theme-dark` class on the `` element; `'system'` follows the system's `prefers-color-scheme`, live. Default `'htmlClassName'`. `backgroundColor`| `ThemedColor` | Colour of the surface behind the chart, in any of the forms under [Colours](#colours). The chart paints it inside the hover dots, in the mask over unfocused bars, as a ring around the heads of event lines and as a halo around the Y-axis labels and the labels of reference lines, hatched ranges and event lines. Defaults to the skin's own background; without it, of the Y-axis labels only `areLabelsContrast` ones get a halo. `areLinesSmooth`| `boolean` | `true` to draw `line` datasets, and the `comparison` line beside them, as monotone curves through their values, never overshooting a value. Default `false`. `areaOpacity`| `number` | Opacity of an `area` fill, from 0 to 1; the outline and dots keep full opacity. Default `1`. `areaBorderColor`| `ThemedColor` | Colour of a 1px outline around each area, and around each run of an area split at a gap: any CSS colour or `{ light, dark }`. A stack draws a boundary two areas share once. `withGradient`| `boolean` | `true` to shade each sector of a `pie` or `donut` chart, and of the pie or donut a zoom into shares opens, from 10% lighter at its inner edge, the centre of a pie, to 10% darker at its outer edge. Default `false`. ### Minimap and range See [Minimap and ranges](https://lovelychart.io/guide/minimap.md). Parameter | Type | Description | ---------|----|----| `withMinimap`| `boolean` | `true` to render the minimap with the draggable range selector below the chart. A swipe down or up its window or one of the window's ears scrolls the page, a swipe across the window drags it, and one across an ear resizes it. Default `false`. `minimapRange`| `[number, number] \| { from, to } \| 'full'` | Initially selected range: a `[begin, end]` tuple of fractions between 0 and 1 (e.g. `[0.8, 1]` for the last 20%), `{ from, to }`, inclusive label indexes (e.g. `{ from: 0, to: 6 }` for the first week of daily labels), or the `'full'` keyword for the entire range. `from` and `to` are rounded and clamped to the labels, as in `hatchedRanges`: a `bar` or `step` chart, or one with bars or steps among its datasets, selects the columns of the labels from `from` to `to`, a `pie` or `donut` sums those labels, and a `line` or `area` chart selects their points and half an interval past either end, within the axis, so the end points stay off the plot edges. A range of no labels, as one with `from` after `to`, takes the default. In the data `onZoom` returns, the indexes count its own labels. Defaults to `[0.8, 1]` when the minimap is shown, otherwise to `'full'`. `limitDate`| `number` | Optional timestamp that locks the labels before it, as data the reader has no access to: the minimap covers them with a blurred mask, a dashed edge and a lock icon in `--minimap-limit-color`, and its window starts no earlier than the first label at or after `limitDate`, at its point or at the start of its column, wherever the reader drags it. A `minimapRange` that starts before that label starts there and keeps its width within the axis, so one that ends before it moves past the locked labels whole. Ignored without `withMinimap`, when `limitDate` falls at or before the first label, which locks none, and when it falls after the label before the last, which leaves the window only the last label. `onLimitedRangeClick`| `() => void` | Optional function called when the reader clicks the mask of `limitDate`, as to offer the data it locks. Without it, the mask lets the pointer through. `isRangeSelectable`| `boolean` | `true` to let a mouse select the visible range on the plot. A press on the plot and a drag across it draw a band in `--range-selection-color` over the Y range, from the press to the pointer, and the release opens a window on the labels under the band: those whose point, or the centre of whose column, it holds, set on them as `minimapRange` sets one, through the transition a drag of the minimap takes, which `onRangeChange` reports frame by frame. A `line` or `area` chart with no bars or steps among its datasets takes two points at least, so a band over one point or none leaves the range as it is, as does a band over no column centre. The minimap window follows the range, from the first label `limitDate` leaves open and no narrower than a drag of its ears leaves it, widened around its middle; a chart without the minimap takes the range alike. A double click on the plot shows the whole range again, on a chart that does not zoom in on a click, as the first click of the two zooms one that does. A press that moves less than 4px across the plot is a click, Escape ends a drag with no change, a release the page never hears, as a context menu takes it, ends the drag with no change, and the click that ends a drag zooms into nothing. A touch keeps selecting a label, and a double tap shows no range. `update()` with `shouldKeepZoom` keeps the range. Ignored on `pie` and `donut` charts, while zoomed and with `noTooltip`. Default `false`. `onRangeChange`| `(range: { from, to } \| undefined) => void` | Optional function called after each frame that draws the labels at a new x, at most once a frame, with the labels of the visible range, `{ from, to }`, inclusive indexes in `labels`: those `getLabelX()` maps, which in the callback gives where that frame drew each, so an element a page places there moves with the canvas. It is called on the first paint, through each frame of a drag or a resize of the minimap window, of the transition to a range selected on the plot or shown whole by `isRangeSelectable`, and of the range transition of a zoom in or out, from the first frame of the data `onZoom` returns, whose labels it indexes then, and on the first paint after `update()`, a resize or an orientation change, even at the same labels; a chart that opens zoomed, by `initialZoom` or an `update()` that keeps the zoom, reports nothing of the overview it hides until the zoomed view shows. A frame that moves no label, as that of a hover, a selection, a legend toggle or a change of the skin, goes unreported. `from` and `to` mean what they mean in `minimapRange`, so passing the range back as `minimapRange` opens a window on the same labels, set on them as `minimapRange` sets one: on their columns, or on their points and half an interval past either end; with `limitDate`, such a window on a `line` or `area` chart from the first label it leaves open starts on that label, keeping its width, and so shows one label more at its end, unless it ends on the last label. Called with `undefined` once no labels are on screen: on the first paint of a `pie` or `donut` chart or of data with no labels, from the first frame of a zoom into shares until the zoom out draws the labels again, and as `destroy()` tears the chart down. A call to `update()` or `destroy()` from within it is safe, and as the first frame of `update()` reports its labels again, a callback that calls `update()` on every report rebuilds the chart on every frame. ### Zoom See [Zoom and drill-down](https://lovelychart.io/guide/zoom.md). Parameter | Type | Description | ---------|----|----| `onZoom`| `(value: number) => Promise` | Optional function which returns `Promise` with data for the zoomed chart (new `data` object). The zoomed data sets its own options, such as `areLinesSmooth`, `isYAxisOutward` and each dataset's `isDashed`, so it repeats those it shares with the chart; `axisTextColor`, `backgroundColor`, `colorScheme` and `ariaLabel` stay the chart's, and a chart that shows no caption, by `noCaption` or text labels, shows none while zoomed. Its datasets take their own colours, from `colors` or each dataset's `color`, on the plot, in the legend, the tooltip and the minimap; 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. Data with another number of datasets than the chart shows in full, without the minimap. `colors`| `Record` | In data that `onZoom` returns, the colours of its datasets by key, `y0` for the first, `y1` for the second and so on, over each dataset's `color`: `{ y0: '#3497ED', y1: '#9ED448' }`. The chart's own data ignores it. `noZoom`| `boolean` | `true` to disable zooming. Default `false`. `zoomType`| `'pie' \| 'donut'` | Chart type shown when a percentage chart is zoomed into a single label: `pie` or `donut`. Default `pie`. `zoomToShares`| `boolean` | `true` to opt a non-percentage chart into zoom-to-shares, so clicking a label drills into a `zoomType` chart of that label's shares. Percentage charts do this implicitly; a stacked chart of absolute values needs the flag, since switching it to `isPercentage` would discard the values the overview exists to show. Ignored when `onZoom` is supplied. Default `false`. `circleLabelsAround`| `number` | How many labels either side of the clicked one the zoomed pie/donut covers. Default `3`, which suits daily data; use `0` to drill into a single label. `initialZoom`| `number \| 'last'` | Open the chart already zoomed on a point, with no overview shown and no transition morph: a label index, or `'last'` for the last point. Works for both shares (pie/donut) and custom `onZoom` charts. Zoom-out afterwards behaves normally. Ignored when the chart is not zoomable. Out-of-range indexes are clamped. `onZoomChange`| `(labelValue: number \| undefined, labelIndex: number \| undefined) => void` | Optional function `(labelValue, labelIndex)` called once a zoom settles, with the value of the zoomed-in label (its timestamp, or the index of a text label) and its index in `labels`, and with `undefined` for both once zoomed out, also when `update()`, unless it keeps the zoom, a resize or an orientation change returns a zoomed chart to its overview. `zoomOutLabel`| `string` | Text of the zoom-out control, in `--zoom-out-text` after a magnifier icon, which takes the place of the title while zoomed, or floats over the plot with `noHeader` or from a header with nothing to show. Default `Zoom out`. `noZoomOutControl`| `boolean` | `true` to leave out the zoom-out control, for a page that zooms out with `zoomOut()` from a control of its own; while zoomed, the header keeps its title. Default `false`. ### Annotations Lines, bands and a previous period drawn with the data. See [Annotations](https://lovelychart.io/guide/annotations.md). Parameter | Type | Description | ---------|----|----| `referenceLines`| `ReferenceLine[]` | Dashed rules at fixed values of the main Y axis: `[{ value, label?, color? }]`. The Y range always reaches each value, stacked charts included, so a line with `color: 'transparent'` draws nothing and only pins the range. `label` is drawn above the right end of the line, none when empty. `color` is any CSS colour or `{ light, dark }`, and defaults to the Y-axis text colour. `label` reads in the direction of the page, so on a right-to-left page a sign before a number moves after it; a number wrapped in U+2066 and U+2069, as `'\u2066-1.2K\u2069'`, keeps its sign first. On a percentage chart `value` is a percentage from 0 to 100 and the range stays 0–100%. Ignored on pie and donut charts. `hatchedRanges`| `HatchedRange[]` | Runs of labels whose values are estimated, partial, still accruing or forecast, hatched across the plot and the minimap: `[{ from, to, label?, color?, hasEdge?, isAccruing?, note?, titleNote? }]`, `from` and `to` inclusive label indexes, rounded and clamped to the labels. 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, as the segment into an estimated value is estimated too, or halfway from it with `isAccruing`, for a period still filling, and ends it halfway to the label after the range. The hatch goes under the lines of a `line` or `step` chart and over the fills of a `bar` or `area` chart, under the comparison line, the mask over unfocused bars and the reference lines; ranges of one colour that touch hatch as one band. Each range keeps its own label and edge: `label` is drawn at the bottom left of the range's hatch, in the axis font size, clear of the Y-axis labels and of the next label, and dropped where it has no room. `hasEdge` draws a dashed rule where the range's hatch starts, none at the first label. `color` is any CSS colour or `{ light, dark }` for the hatch, the edge and the label, and defaults to the Y-axis text colour. `note` and `titleNote` are notes of the tooltip at each label of the range, under the rows and beside the title, as `resolveTooltipNotes` gives them. The minimap draws the hatch alone, and a sparkline the hatch and the edges. Ignored on pie and donut charts, a zoom into shares included; the data `onZoom` returns sets ranges of its own. `eventLines`| `EventLine[]` | Vertical rules at moments of the labels, such as a launch or a change in how the data is collected, and pins that carry a note: `[{ labelIndex, offset?, label?, color?, isDashed?, isDotted?, withHead?, hint? }]`, `labelIndex` rounded, and a rule outside the labels dropped. `offset`, clamped to 0–1, places the rule that fraction through the label's interval, as `getLabelX()` maps it: from its point to the next one on a `line` or `area` chart, where `0`, the default, is the point, and across its column on a `bar` or `step` chart, or one with bars or steps among its datasets, where `0` is its start and `0.5`, the default, its centre. The last point of a `line` or `area` chart has no next one and keeps its rule at the point. Each rule runs from the bottom of the Y range through the room above it, over the datasets, the hatches and the comparison line and under the reference lines and the axis labels, and follows the range and the zoom. A rule is a solid 1px line, which `isDashed` draws in 6px dashes 4px apart and `isDotted` in 2px dots 3px apart, `isDashed` or not, as those of a dataset. `withHead` makes the rule a pin, topped by a head at the top of the canvas: a disc of its colour 8px across, ringed in the background colour, over the data and the axis labels. `label` reads bottom to top from the top of its rule, or from under its head, in the axis font size: before the rule, or after it where it would cover the Y-axis labels, those of an `isYAxisOutward` column included, or leave the plot area. It is dropped where it fits on neither side or runs longer than its rule, and where the label of a later rule crowds it. `color` is any CSS colour or `{ light, dark }` for the rule, its head and the label, and defaults to the Y-axis text colour. `hint` is a note of the tooltip at the label of `labelIndex`, under the rows, as a `note` of `hatchedRanges` is: after the notes of the ranges and before those of `resolveTooltipNotes`, split into lines at `\n`, a line shown already left out. A sparkline draws the rules and their heads without their labels, and the minimap draws none. Ignored on pie and donut charts, a zoom into shares included; the data `onZoom` returns sets rules and hints of its own. `comparison`| `Comparison` | A previous period, drawn as a dashed line: `{ name, color?, values }`. `values` holds the previous values per dataset, in the order of `datasets`, each aligned with `labels`; the line draws their sum over the datasets on screen, and a `null` leaves a gap. `color` takes any of the forms under [Colours](#colours), `DEFAULT_COMPARISON_COLOR`, `#6B7280`, by default. The legend names it beside a dashed swatch, and the tooltip lists it first with the change of the current total in percent. Ignored on percentage, pie and donut charts. ### Tooltip and selection The tooltip lists each dataset on screen with a non-zero value at the label: a swatch of its colour, its name and its value in the text colour, from the largest value down. The swatch of a dashed or dotted line is a dashed or dotted outline. A `comparison` row comes first, beside a dashed swatch of its colour, in `--tooltip-muted-text-color` with its value in the normal weight, and set apart from the rest by a rule in `--tooltip-separator-color`. Its change is bold and tinted by `--tooltip-change-positive` or `--tooltip-change-negative`, unless it rounds to 0%, which keeps the colour and weight of its value. Stacked and percentage `bar`, `step` and `area` charts add a Total row. Notes of `hatchedRanges` and `resolveTooltipNotes` stand beside the title and under the rows, and the hints of `eventLines` under the rows, in `--tooltip-muted-text-color`. A pie or donut lists the sector under the pointer alone. See [Tooltip](https://lovelychart.io/guide/tooltip.md) and [Events and external control](https://lovelychart.io/guide/interaction.md). Parameter | Type | Description | ---------|----|----| `noTooltip`| `boolean` | `true` to leave out the hover layer, its line, dots and 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` still opens a zoom. Default `false`. `isTooltipOrderFixed`| `boolean` | `true` to list the tooltip rows in the order of the legend, after the `comparison` row. When more than 12 rows would show, the largest values still decide which ones do. Default `false`. `isTooltipTotalInTitle`| `boolean` | `true` to put the total of a stacked or percentage `bar`, `step` or `area` chart beside the tooltip title, in place of the Total row. Default `false`. `formatTooltipValue`| `(value: number) => string` | Optional function formatting a number of the tooltip; `valuePrefix` and `valueSuffix` still wrap the result. It formats the total on the `secondaryYAxis` scale too, which the `prefix` and `suffix` of that scale wrap instead. `resolveTooltipTotal`| `(labelValue: number, datasetIndexes: number[], labelIndex: number) => number \| null \| undefined` | Optional function `(labelValue, datasetIndexes, labelIndex) => number \| null \| undefined` giving the total of a stacked chart's tooltip, for the label's value (its timestamp, or the index of a text label), the indexes of the datasets on screen and the label's index in `labels`. `undefined` keeps the sum of the rows, `null` shows `—`. The comparison change and the total on the `secondaryYAxis` scale read this total too. `resolveTooltipNotes`| `(labelValue: number, datasetIndexes: number[], labelIndex: number) => TooltipNotes \| undefined` | Optional function `(labelValue, datasetIndexes, labelIndex) => { titleNote?, notes? } \| undefined` giving the notes of the tooltip at a label, for its value and the indexes of the datasets on screen, as `resolveTooltipTotal` takes them, and its index. `titleNote` stands after the date, before the total of `isTooltipTotalInTitle`. `notes` are lines below the rows, under a rule in `--tooltip-separator-color`, as wide as the rows and wrapped to them. The notes of the `hatchedRanges` that hold the label come first, in their order, then the hints of the `eventLines` at the label, in theirs, then these; each note splits into lines at `\n`, a line shown already is left out, and the text shows as it is, never as HTML. This `titleNote` wins over those of the ranges, of which the first one wins. The notes change with the rows, for a pointer, a touch or `selectLabel()`. Ignored on pie and donut charts. `onSelectedIndexChange`| `(labelIndex: number \| undefined) => void` | Optional function called when the selected label changes, by pointer, touch, keyboard or `selectLabel()`, with its index, not its value, and with `undefined` once nothing is selected: the pointer leaves the chart, `selectLabel(undefined)`, `update()` unless it keeps the selection, a resize, or the selected label leaving the visible range. `onTooltipChange`| `(tooltip: TooltipContent \| undefined) => void` | Optional function called when what the tooltip shows changes, as another label is selected or a dataset is shown or hidden, with `{ labelIndex, title, rows, total?, comparison? }`, after `onSelectedIndexChange`, and with `undefined` once it shows nothing, as when nothing is selected. `title` is the title of the tooltip. `rows` holds each dataset on screen, in the order of `datasets`, as `{ datasetIndex, name, value }`, its value at the label, zero included and `null` for a gap. `total` comes with a stacked or percentage `bar`, `step` or `area` chart, as its Total row or title shows it: what `resolveTooltipTotal` gives, or else the sum of the rows. `comparison` comes with a `comparison`, as `{ name, value, change? }`: the previous value at the label and the change of the total against it in percent, unrounded, where the tooltip shows one. A pie or donut reports none. It goes on reporting with the balloon hidden by `--lovely-chart-balloon-display`, for a readout of the page. `isKeyboardSelectable`| `boolean` | `true` to make the plot focusable, in the tab order of the page. Arrow Left and Arrow Right then step the selection to the previous or the next label, and Home and End to the first or the last label of the visible range, as `selectLabel()` does; with nothing selected, an arrow selects the last label. A key pressed with Alt, Ctrl or Meta stays the browser's. The plot keeps the focus through `update()` and a resize, which rebuild it. Ignored on pie and donut charts, and the pie or donut a zoom opens leaves the tab order while it shows. Default `false`. ## Instance methods The created instance exposes the following methods (the `LovelyChartInstance` type describes `update` and `destroy` structurally, e.g. for test stubs): Method | Description | ---------|----| `update(newData, options?)`| Replaces the current data with `newData` (same shape as the initial `data` argument) and re-renders, at once or, with `isAnimated`, through a cross-fade. Resets transient view state (zoom, range, filter, selection) and ends a drag, a long press or a hover in progress, unless `options` keeps part of the view: see [Update options](#update-options). The chart keeps a reference to `newData`, as it does to `data`, and builds from it again on a resize or an orientation change, so a change made to the object afterwards shows from that build on; pass a new object for new data instead. No-op after `destroy()`. `selectLabel(labelIndex)`| Selects the label at `labelIndex` as hovering it would: shows its tooltip, focuses its bar and calls `onSelectedIndexChange` and `onTooltipChange`. The selection holds while the pointer moves elsewhere on the page and follows its label through a range change; the pointer over the chart takes it over, and it clears once its label leaves the visible range: the labels whose point, or the centre of whose column, lies in the window the plot shows, or in a window too narrow to hold one, the labels of the points either side of it or of the columns it shows. `selectLabel(undefined)` clears the selection. Ignored for an index outside the visible range, on pie and donut charts, with `noTooltip` and before the first paint, the frame after the chart is created or updated. No-op after `destroy()`. `refreshColors()`| Reads the `var()` colours of the params again and repaints the chart in them in place, keeping its zoom, range, legend filter and selection: for custom properties that the page changes on another trigger than the skin, such as a `data-theme` attribute. A change of the skin reads them by itself, as [Colours](#colours) describes. No-op after `destroy()`. `setLegendContainer(element)`| Moves the legend into `element`, or back to the end of the chart with `undefined`, without a rebuild: its buttons keep the datasets they hide, and the chart keeps its zoom, range and selection. The legend takes its [spacing variables](https://lovelychart.io/guide/css.md#spacing-the-chart) from its new place, and stays there through a zoom, a resize and an orientation change; `update()` places it by the `legendContainer` of its new data. The element that held it keeps nothing of the chart, and a call with the element that holds it leaves it in place among the elements of the page. No-op after `destroy()`. `getLabelX(labelIndex, offset?)`| The x of the label at `labelIndex` in px from the left of the plot area the `--lovely-chart-plot-area-*` variables describe, where the last frame the chart drew put it: where its value draws, at its point on a `line` or `area` chart and at the centre of its column on a `bar` or `step` chart. `offset`, from 0 to 1, takes that fraction through the label's interval instead: from its point to the next one on a `line` or `area` chart, where `0` is the point, and across its column on a `bar` or `step` chart, or one with bars or steps among its datasets, where `0` is its start and `0.5` its centre. It follows the canvas frame by frame, so through the transition of a pan or a zoom it gives where the label stands on screen, and `onRangeChange` reports each frame that moves the labels; from the first frame of the data `onZoom` returns, it maps that data's labels. A panned window runs past the plot area, so a label at its edge can map below 0 or past the area's width. Returns `undefined` for an index outside the labels `onRangeChange` reports, before the first frame of the chart, of `update()`, of a resize and of the data a zoom swaps in, while a chart that opens zoomed waits for the data of the zoom, on pie and donut charts, a zoom into shares from its start included, and after `destroy()`. `zoomOut()`| Zooms a zoomed chart out to its overview as its zoom-out control does, for a page that draws a header or a zoom-out control of its own and leaves out the chart's control with `noZoomOutControl`. Starts on the next frame, and only if the chart is zoomed in then: from the moment `onZoomChange` reports a zoom, even from within that callback, until a zoom out starts. No-op after `destroy()`. `setLoading(isLoading)`| Shows the chart as loading, as the `isLoading` parameter does, and `setLoading(false)` as loaded, without a rebuild: the data on screen dims or shows in full, or data with no labels shows or leaves its skeleton, and the zoom, the range, the datasets hidden in the legend and the selected label stay as they are, with no callback. A resize keeps the state, and `update()` takes the one of its `isLoading`. No-op after `destroy()`. `destroy()`| Tears down the chart: removes the DOM subtree from `element` and the `--lovely-chart-plot-area-*` and `--lovely-chart-plot-padding-top` variables from its style, calling `onPlotAreaChange` with `undefined`, and `onRangeChange` with `undefined` when it last reported labels, detaches all global listeners (window `resize` / `orientationchange`, document `mousemove` / `touchstart` and those of a drag in progress, theme `MutationObserver`, layout `ResizeObserver`, the `prefers-color-scheme` media query `change`, `document.fonts` `loadingdone`), cancels pending animation frames and timeouts, and calls back nothing after it. Idempotent. Call this from your framework's cleanup hook (e.g. React `useEffect` cleanup) to avoid resource leaks. ## Update options The second argument of `update()`, of the `LovelyChartUpdateOptions` type, keeps parts of the view the reader has and animates the change. Each option is `false` by default, which resets that part or swaps the data at once. Option | Description | ---------|----| `shouldKeepFilter`| `true` to keep the datasets the reader showed or hid in the legend, matched by their place in `datasets`, or by `name` when `newData` has another number of datasets. A dataset with no match starts as its `isInitiallyHidden` says, and so does every dataset where the match would hide them all, which the legend never lets the reader do. `onHiddenSeriesChange` is called once the new data is built when the names or the indexes of the hidden datasets differ from those before. `shouldKeepZoom`| `true` to keep the window, of the minimap or of a range selected on the plot, and the zoom while `newData` has the same `labels`. A zoomed chart opens zoomed into the same label, with no overview shown and no transition morph, as `initialZoom` opens it, and calls `onZoom` again for it; a zoom out returns to the kept window. `onZoomChange` goes uncalled for a zoom it already reported, is called with the label's value and index once a zoom still on its way in shows on the rebuilt chart, and with `undefined` for both when the zoom ends: when the labels differ, when `newData` cannot zoom, or when `onZoom` fails. `shouldKeepSelection`| `true` to keep the selected label, by pointer, touch, keyboard or `selectLabel()`, at the index of the label of the same value in `newData`, while there is one in the window the chart opens on. A selection by pointer or touch still clears as the pointer leaves the chart or a touch lands elsewhere, and one by the keyboard or `selectLabel()` holds. `onSelectedIndexChange` is called on the first frame of the new data only when the index changes, and `onTooltipChange` only when what the tooltip shows changes, and both with `undefined` when the selection ends: its label is gone or outside the window, or a zoom shows or is kept. `isAnimated`| `true` to cross-fade the chart into `newData` over 400ms. The chart it replaces, with its plot, axes, header, minimap and legend, stays in the new chart's place, under it, as it fades out and the new one fades in. It takes no room in the layout, so the page lays out around the new chart at once, and no pointer, focus or assistive technology reaches it; while it is taller than the new chart, it covers the content that follows. A legend in `legendContainer` cross-fades in its place there, the replaced one over the new one. Positioned elements of the page after the chart in `element` paint over both charts, and those before it under both. Another `update()` with `isAnimated` fades the chart out from the opacity it has reached, while the charts before it go on fading out; one without it, a resize, an orientation change or `destroy()` ends the fades at once. Ignored while the system asks for reduced motion (`prefers-reduced-motion: reduce`). ## Colours Every colour parameter, `datasets[*].color`, `colors`, `comparison.color`, `axisTextColor`, `backgroundColor`, `areaBorderColor`, `referenceLines[*].color`, `hatchedRanges[*].color` and `eventLines[*].color`, takes a CSS colour for both skins, or `{ light, dark }`, one for each. Each also takes `#RRGGBB/alpha`, a hex colour at an opacity. A colour can be a `var()` of a custom property of the page, alone or inside a colour function such as `color-mix()`. The chart computes it on a hidden element of its own inside `element`, so it reads the custom properties of `element` and its ancestors, and the chart's skin variables such as `--text-color`, and any colour they hold works: hex, `rgb()`, `color-mix()`, `oklch()` and the rest. It reads them when it is built, on `update()` and on a zoom, and again on each change of the `class` of ``, where the `theme-dark` class switches the skin, and, with `colorScheme: 'system'`, of `prefers-color-scheme`. It then repaints in place, keeping its zoom, range, legend filter and selection. `refreshColors()` reads them again for custom properties that the page changes on another trigger, such as a `data-theme` attribute. The plot, the minimap, the legend buttons, `--lovely-chart-series-color` and the tooltip swatches take the colour of the skin on screen. ```js const chart = new LovelyChart(element, { type: 'line', labels, datasets: [ { name: 'Revenue', color: 'var(--color-accent)', values: revenue }, { name: 'Refunds', color: { light: '#E65850', dark: '#F07068' }, values: refunds }, ], axisTextColor: 'var(--color-text-muted)', backgroundColor: 'var(--color-surface)', }); // The page's tokens follow a `data-theme` attribute, which the chart does not watch document.documentElement.dataset.theme = 'dark'; chart.refreshColors(); ``` ### Default colours The package exports the colours a chart gives the datasets with no `color`, for elements of the page that show the same series, such as a table beside the chart: Export | Description | ---------|----| `DEFAULT_COLORS`| The eight default colours in order, as a frozen array: `#3497ED`, `#2373DB`, `#9ED448`, `#5FB641`, `#F5BD25`, `#F79E39`, `#E65850` and `#5D5CDC`. `getDefaultColors(datasetCount)`| The default colours of a chart of `datasetCount` datasets, one per dataset, in a new array. The chart gives them in order to the datasets with no `color`, so where none has one, the dataset at index `i` takes the colour at `i`. Fewer than eight datasets take a subset of `DEFAULT_COLORS` whose hues stand apart, as `#3497ED` and `#9ED448` for two; more take `DEFAULT_COLORS` again from the first. `DEFAULT_COMPARISON_COLOR`| The colour of the `comparison` line when it sets none, `#6B7280`. ```js import { getDefaultColors } from 'lovely-chart'; // The colours a chart of these providers gives them, for a table beside it const colors = getDefaultColors(providers.length); const providerColors = Object.fromEntries(providers.map((name, i) => [name, colors[i]])); ``` ## Types The package ships its declarations, `dist/LovelyChart.d.ts`, and exports the types of its parameters: Type | Description | ---------|----| `LovelyChartParams`| The parameters of a chart, the `data` of the constructor and of `update()`: see [Chart options](#chart-options). `LovelyChartDatasetParams`| A dataset: `{ name, values, color?, isInitiallyHidden?, isDashed?, isDotted?, type? }`, the `datasets[*]` entries of [Chart options](#datasets). `LovelyChartUpdateOptions`| The second argument of `update()`: `{ shouldKeepFilter?, shouldKeepZoom?, shouldKeepSelection?, isAnimated? }`, see [Update options](#update-options). `LovelyChartInstance`| `Pick`, the methods a test stub or a wrapper of a framework needs. `ChartType`| `'line' \| 'bar' \| 'step' \| 'area' \| 'pie' \| 'donut'`, the [`type`](#type) of a chart. `LabelType`| `'year' \| 'month' \| 'week' \| 'day' \| 'hour' \| '5min' \| 'dayHour' \| 'text'`, the kind of the X-axis labels, [`labelType`](#labelType). `ThemedColor`| `string \| { light: string; dark: string }`: a CSS colour for both skins, or one for each. See [Colours](#colours). `DateLocale`| `{ months?, monthsFull?, weekDays?, weekDaysShort?, weekOf? }`, the localized names of [`dateLocale`](#dateLocale): arrays of 12 months or 7 weekdays from Sunday, and the words before the start date of a week. `SecondaryYAxisConfig`| `{ label: string; multiplier: number; prefix?: string; suffix?: string }`, the scale of [`secondaryYAxis`](#secondaryYAxis). `ReferenceLine`| `{ value: number; label?: string; color?: ThemedColor }`, an entry of [`referenceLines`](#referenceLines). `HatchedRange`| `{ from: number; to: number; label?: string; color?: ThemedColor; hasEdge?: boolean; isAccruing?: boolean; note?: string; titleNote?: string }`, an entry of [`hatchedRanges`](#hatchedRanges). `EventLine`| `{ labelIndex: number; offset?: number; label?: string; color?: ThemedColor; isDashed?: boolean; isDotted?: boolean; withHead?: boolean; hint?: string }`, an entry of [`eventLines`](#eventLines). `Comparison`| `{ name: string; color?: ThemedColor; values: (number \| null)[][] }`, the previous period of [`comparison`](#comparison). `TooltipNotes`| `{ titleNote?: string; notes?: string[] }`, what [`resolveTooltipNotes`](#resolveTooltipNotes) returns. `TooltipContent`| `{ labelIndex: number; title: string; rows: { datasetIndex: number; name: string; value: number \| null }[]; total?: number \| null; comparison?: { name: string; value: number \| null; change?: number } }`, what [`onTooltipChange`](#onTooltipChange) reports. --- # CSS variables and classes The chart reads custom properties for its sizes, its spacing, its fonts and the colours of its skins, and sets a few of its own for the page to place elements by. Set them on the chart's element or any ancestor, as a media query or a theme of the page needs. ```css .chart { --lovely-chart-plot-height: 240; --lovely-chart-font-family: inherit; --lovely-chart-inset: 0; } @media (min-width: 60rem) { .chart { --lovely-chart-plot-height: 360; } } ``` ## Layout See [Layout, sizing and fonts](https://lovelychart.io/guide/layout.md). Variable | Description | ---------|----| `--lovely-chart-plot-height`| Plot canvas height, read from the chart element or an ancestor, ahead of `plotHeight`: a unitless number of px, `px` or `rem`. `--lovely-chart-header-height`| Height of the header band, and line height of its title and caption, read from the chart element or an ancestor. Default `30px`. `--lovely-chart-header-margin-top`| Space above the header band, read from the chart element or an ancestor. Default `0`. `--lovely-chart-plot-margin-top`| Space between the header band and the plot canvas, read from the chart element or an ancestor. Default `10px`; a sparkline has none. The hover line and dots of the tooltip follow the plot canvas when these variables or a style of the page move it by resizing the chart's layout or its header, as a folded header. `--lovely-chart-empty-header-height`| Height of a header with nothing to show, with no `title` and no caption because of `noCaption` or text labels, read from the chart element or an ancestor: 0 by default, so the plot starts at the top of the chart, and while zoomed the zoom-out control floats over the top inline-start corner of the plot. A length such as `1rem` keeps a band, as to level the plots of a row where another chart shows a caption; a header that shows something takes `--lovely-chart-header-height`. ## Typography Variable | Description | ---------|----| `--lovely-chart-font-family`| Font family of the chart's text, read from the chart element or an ancestor: the header, the legend, the tooltip and the labels the canvas draws, those of the axes in the regular weight, and those of reference lines, hatched ranges, event lines and pie sectors in weights of their own. Default `'-apple-system', 'HelveticaNeue', Helvetica, Arial, sans-serif`. A custom property set to `inherit` takes the variable of the parent, not its font, so a chart in the font of the page takes the page's family list, or a `var()` that holds it. A legend in `legendContainer` reads it from that element or an ancestor, and keeps the family of that element while it is unset. `--lovely-chart-font-weight`| Regular weight of the chart's text, read from the chart element or an ancestor: the legend, the names in the tooltip and the axis labels. Default `300`. A legend in `legendContainer` reads it from that element or an ancestor. `--lovely-chart-font-weight-bold`| Weight of the chart's bold text, read from the chart element or an ancestor: the header and its zoom-out control, the tooltip title and the total beside it, the values, the Total row, a rise or a fall against the `comparison` and the shares of a percentage chart. Default `bold`. ## Spacing the chart The spacing variables, `--lovely-chart-inset` to `--lovely-chart-button-font-size`, apply from `element`, any ancestor of it or `.lovely-chart--container`, so one rule can space every chart on a page. A legend in `legendContainer` takes them from that element and its ancestors. The chart sizes the minimap canvas to `--lovely-chart-inset` as it lays out: when it is built, on `update()`, a resize or an orientation change. ```css /* A card whose own padding insets the chart, which ends at the last row of a legend of small pills */ .card { padding: 16px; --lovely-chart-inset: 0; --lovely-chart-legend-padding-bottom: 0; --lovely-chart-button-padding: 4px; --lovely-chart-button-radius: 8px; --lovely-chart-button-font-size: 12px; } ``` Variable | Description | ---------|----| `--lovely-chart-inset`| Side inset of the header, the minimap and the legend. Default `10px`. The minimap canvas takes the width it leaves. The plot keeps its own 10px gutter, so another inset moves the header, the minimap and the legend off the line of its Y-axis labels and grid. `--lovely-chart-minimap-margin-bottom`| Space under the minimap, above the legend when the chart holds it. Default `16px`. `--lovely-chart-legend-gap`| Space between the legend entries, as the CSS `gap`: one length, or a row gap and a column gap. Default `8px 6px`. `--lovely-chart-legend-padding-bottom`| Space under the last row of the legend. Default `24px`; `0` ends the chart at the legend. `--lovely-chart-button-padding`| Padding on every side of a legend button, one length, which also places its check mark. The comparison entry takes it above and below its name. Default `7px`. `--lovely-chart-button-radius`| Corner radius of a legend button. Default `18px`. `--lovely-chart-button-font-size`| Font size of the legend buttons and the comparison entry. Defaults to the font size around them, the chart's 13px. ## Skin colours The day and the night skin set these colours on `.lovely-chart--container`. See [Theming and colours](https://lovelychart.io/guide/theming.md). Variable | Description | ---------|----| `--background-color`, `--text-color`, `--grid-lines`, `--tooltip-background` and the other variables on `.lovely-chart--container`| The colours of the day and the night skin. Night colours of your own go under `html.theme-dark .lovely-chart--container:not(.lovely-chart--container-scheme-system)` for the default `colorScheme`, and under `.lovely-chart--container.lovely-chart--container-scheme-system` inside `@media (prefers-color-scheme: dark)`, in a stylesheet after the library's, for `'system'`, so neither reaches a chart of the other scheme. `--tooltip-change-positive`, `--tooltip-change-negative`| Colours of a rise and a fall of the `comparison` change in the tooltip. `--tooltip-muted-text-color`| Colour of the `comparison` row and the notes of the tooltip. Defaults to a mix of 70% `--text-color` and 30% `--tooltip-background`, which follows a skin of your own and reaches a contrast of 4.5:1 on the tooltip background in the day and the night skin. A colour of your own goes per skin, as the colours above. `--tooltip-separator-color`| Colour of the rule under the `comparison` row of the tooltip and of the rule over its notes. Defaults to `--grid-lines`. `--tooltip-border`| Border of the tooltip balloon, as `1px solid #D2D5D7`. Default `none`. `--skeleton-color`| Colour of the skeleton a loading chart draws in place of data with no labels, `isLoading`, one in each skin as the colours above. A legend in `legendContainer` reads it from that element or an ancestor, and takes a translucent grey while it is unset. `--range-selection-color`| Colour of the edges of the band `isRangeSelectable` draws while a mouse drags across the plot, and, at 12% over the plot, of its fill, one in each skin as the colours above: `#108BE3` by day and `#48AAF0` by night. The band is `.lovely-chart--range-selection`. The skins declare these values, in the DOM parts of the chart: its header, legend, tooltip and minimap. The canvas draws the grid, the axis labels and the hover dots in colours of its own skin, which [`axisTextColor`](https://lovelychart.io/guide/api.md#axisTextColor) and [`backgroundColor`](https://lovelychart.io/guide/api.md#backgroundColor) set. Skin variable | Day | Night | Colours | ---------|-----|-------|----| `--background-color` | `#ffffff` | `#242F3E` | The backdrop of the zoom-out control that floats over the plot `--text-color` | `#222222` | `#ffffff` | The text of the header, the legend and the tooltip `--tooltip-background` | `#ffffff` | `#1c2533` | The tooltip balloon `--grid-lines` | `rgba(24, 45, 59, 0.1)` | `rgba(255, 255, 255, 0.1)` | The ring of a tooltip swatch, and the default of `--tooltip-separator-color` `--zoom-out-text` | `#108BE3` | `#48AAF0` | The zoom-out control `--minimap-mask` | `rgba(226, 238, 249, 0.6)` | `rgba(48, 66, 89, 0.6)` | The minimap outside its window `--minimap-slider` | `#C0D1E1` | `#56626D` | The frame and the ears of the minimap window `--minimap-limit-color` | `#616770` | `#BFC0C2` | The dashed edge and the lock of the `limitDate` mask `--tooltip-change-positive` | `#108BE3` | `#48AAF0` | A rise against the `comparison` `--tooltip-change-negative` | `#E65850` | `#F07068` | A fall against the `comparison` `--skeleton-color` | `rgba(24, 45, 59, 0.1)` | `rgba(255, 255, 255, 0.1)` | The skeleton of a loading chart `--range-selection-color` | `#108BE3` | `#48AAF0` | The band of a range selection ## Tooltip Variable | Description | ---------|----| `--lovely-chart-balloon-display`| The `display` of the tooltip balloon, read from the chart element or an ancestor: `block` by default. `none` hides the balloon alone and keeps the rest of a selection, the hover line and dots, the focus of a bar and the calls of `onSelectedIndexChange` and `onTooltipChange`, so a media query can swap the balloon for a readout of the page. A touch screen zooms by a tap on the balloon, so there `none` takes that zoom away too. ### Styling the tooltip The tooltip keeps these classes from release to release, for the rules of a page; its other classes are internal. Its text takes `--text-color`, and its background, the `comparison` row and the notes, the rules under that row and over the notes, the tones of the change and the border of the balloon take the `--tooltip-*` variables above. Class | Element | ---------|----| `.lovely-chart--tooltip-balloon`| The balloon: its shadow, padding and radius. A night rule of your own under `html.theme-dark .lovely-chart--tooltip-balloon` is as specific as the library's. `.lovely-chart--tooltip-title`| The title: the date or the label, and at its far end the total of `isTooltipTotalInTitle`. `.lovely-chart--tooltip-title-total`| The total beside the title, with `isTooltipTotalInTitle`. `.lovely-chart--tooltip-title-note`| The `titleNote` of `resolveTooltipNotes` or `hatchedRanges`, inside the first `` of the title after the date, in `--tooltip-muted-text-color`. `.lovely-chart--tooltip-dataset`| A row: a swatch, a name and a value. The `comparison` row is a row too, and the Total row and the `secondaryYAxis` row are rows with a name and a value but no swatch. `.lovely-chart--tooltip-dataset-value`| The value at the end of a row, in bold tabular figures; that of the `comparison` row is in the normal weight. `.lovely-chart--tooltip-dataset-comparison`| The `comparison` row, in `--tooltip-muted-text-color` above a rule in `--tooltip-separator-color`. `.lovely-chart--tooltip-swatch`| The swatch of a row, in `--lovely-chart-series-color`, the colour of its dataset or line. With `data-dashed` or `data-dotted` it is a dashed or dotted outline. `.lovely-chart--tooltip-change[data-tone]`| The change of the `comparison` row, inside its value. `data-tone` is `positive` or `negative` for a rise or a fall, bold in `--tooltip-change-positive` or `--tooltip-change-negative`, and `neutral` for a change that rounds to 0%, which keeps the colour and weight of its value. `.lovely-chart--tooltip-notes`| The notes under the rows, the last child of the balloon, with a `
    ` per line, in `--tooltip-muted-text-color` under a rule in `--tooltip-separator-color`. Hidden while empty. ## Set by the chart The chart writes these on elements of its own and on `element`, for the page to read. See [Overlays and custom marks](https://lovelychart.io/guide/overlays.md). Variable | Description | ---------|----| `--lovely-chart-series-color`| Set by the chart on each legend button, on the comparison legend entry and on each tooltip swatch: the colour of its dataset or line in the skin on screen, as `rgba()`. A legend button takes its outline, its label and its checked fill from it. `--lovely-chart-plot-area-left`, `--lovely-chart-plot-area-top`, `--lovely-chart-plot-area-width`, `--lovely-chart-plot-area-height`| Set by the chart on `element`, as px lengths from the inside of its border: the data area of the plot, where a window over every label and the Y range draw. It runs from the start of the plot, after an `isYAxisOutward` column, to its end, and from the top of the Y range to the X-axis baseline. A pie or donut sets the square around its circle, and a sparkline its plot inset by 2px. The chart sets them from its first paint, the frame after it is created, and rewrites them when the area changes: on `update()`, a resize or an orientation change, a zoom into data of another label column or into a pie, when a web font of the page changes the axis font, and when a style of the page moves the plot by resizing the chart's layout or its header, as a header folded while its caption is empty. `destroy()` removes them. `--lovely-chart-plot-padding-top`| Set by the chart on `element` beside the `--lovely-chart-plot-area-*` variables, and removed with them: the room in the plot above the top of the Y range, `15px`, or `2px` on a sparkline, for marks that rise above the data.