Using Tabler Charts

Everything you need to put a chart on a page: install, pass data, pick a type, style it with CSS. The Demos page has a live, editable example of every chart type with its code.

Install

npm install @tabler/charts

The package has no dependencies and ships ES modules with TypeScript types. It is a pre-release: the API may still change.

Quick start

Import a chart type and the stylesheet, give Chart an element (or a selector) and a config. The chart fills its container's width and follows it when it resizes.

import { Chart, line } from '@tabler/charts'
import '@tabler/charts/style.css'

const chart = new Chart('#sales', {
  type: line,
  data: {
    labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
    series: [
      { name: 'Revenue', values: [42, 51, 47, 63, 58, 71] },
      { name: 'Costs', values: [31, 35, null, 40, 38, 44] }, // null leaves a gap
    ],
  },
  y: { format: { style: 'currency', currency: 'USD' } },
  locale: 'en-US',
})
The result. Hover it, or focus it and use the arrow keys.

The height is the width divided by aspectRatio (2 by default), so the chart needs no fixed size of its own. Give the container a width and the chart does the rest.

Data

Most charts (line, area, bar, radar, heatmap) take categories and series: one label per category and, for every series, one value per category.

data: {
  labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
  series: [
    { name: 'Visitors', values: [820, 932, 901, 934, 1290] },
    { name: 'Sign-ups', values: [62, 73, 70, 73, 99], color: 'var(--tc-color-4)' },
  ],
}

A series takes name and values, and optionally id (a stable identity when names change), color, dash, width, class and hidden.

Other types have the shape of their data: a pie or donut takes [{ name, value }], a scatter takes series of { x, y, size? } points, a calendar takes [{ date, value }], a candlestick [{ x, open, high, low, close }], a sparkline a plain number[] and a gauge a number.

Data from an API does not have to be clean. A value that is not a finite number (null, NaN, '42', an object) is a gap, and a chart never throws over it. Numbers in strings are not parsed: convert them first.

Chart types

Every type is an import of its own. Pass it as type; the options it understands are type-checked with it.

import { area, bar, calendar, candlestick, donut, gauge, heatmap,
         line, parliament, percentageBar, pie, radar, sankey, scatter, sparkline, treemap } from '@tabler/charts'
TypeDataNotable options
line{ labels, series }curve ('monotone', 'linear', 'step'), points ('none', 'last', 'all'), stacked, connectNulls
area{ labels, series }as line, filled; fill: 'gradient' | 'solid'
bar{ labels, series }stacked (true or 'percent'), orientation: 'horizontal', radius, gap; series[].type: 'line' mixes in a line
pie, donut[{ name, value }]innerRadius, gap, cornerRadius, center (text in the middle), maxSlices (the rest is grouped into othersLabel)
gaugea number, or ringsmax, startAngle, angle (270 for a dial), thickness, center
parliament[{ name, seats }]total (vacant seats), rows, angle (180 for a hemicycle), innerRadius, center
treemap[{ name, value }], or groups [{ name, children }]gap, radius, labels, format; --tc-treemap-opacity fades the tiles
percentageBar[{ name, value }]order: 'data' | 'size', maxSlices (the rest is grouped into othersLabel), gap, radius, format; a strip 16 px tall unless height is set
radar{ labels, series }grid: 'polygon' | 'circle', fill, points
scatter{ series: [{ name, points }] }radius, size; points with size are bubbles
heatmap{ labels, series } (rows)min, max, ranges, colors
calendar[{ date, value }]weeks, from, to, weekStart, levels, colors ('diverging')
candlestick[{ x, open, high, low, close }]time axis, maxCandleWidth
sparklinenumber[]variant ('line', 'area', 'bar', 'tristate'), markers: 'minmax'
Stacked bars with a line series
Donut with a center label
Sparkline, the smallest chart

Options every chart takes

OptionDefault
aspectRatio2Width to height; height: 'container' follows the container instead
title, descriptionAccessible name and description of the chart
localeruntime defaultFor number and date formatting; set it for server rendering
legendfor 2+ seriesfalse, true or { position: 'bottom' }
tooltiptruefalse, or { theme, format, footer }: theme: 'light' for a white tooltip instead of the dark one, format and footer for custom content
crosshairtrue
valueLabelsfalseValues written on the marks; { points: 'all' } for every point
animatetrueTransitions between data; off under prefers-reduced-motion
syncA group name: charts of one group share the hover
patterns'auto'Pattern fills so series do not depend on color; 'auto' is forced colors only
downloadtrue adds a PNG/SVG menu in the corner
classExtra classes on the <svg>, for your CSS

Axes and annotations

Cartesian charts share an x and a y axis. format takes Intl.NumberFormat options or a function; notation: 'compact' shortens long numbers ("1.2M").

new Chart('#el', {
  type: line,
  data,
  x: { type: 'time' },                      // labels are dates: real distances, calendar ticks
  y: { min: 0, ticks: 5, format: { notation: 'compact' } },
  annotations: [
    { y: 99.9, label: 'SLA' },              // a line at a value
    { y: [40, 60], label: 'Normal' },       // a band between values
    { x: 'Jun', label: 'Launch' },          // a line at a category (or a date)
  ],
})

y also takes max, zero, nice, scale: 'log', grid and show; x takes utc, grid, line and show.

Updating a chart

New data morphs the chart in place. Updates are batched into one animation frame.

chart.setData(data)                   // new data animates from the old
chart.update({ stacked: true })       // merge options, re-render
chart.setConfig({ type: bar, data })  // replace every option
chart.toggleSeries('Costs')           // by name, id or index
chart.highlightIndex(2)               // as the keyboard does
chart.clearHighlight()
chart.resize()
chart.destroy()                       // when the chart goes away

const off = chart.on('hover', ({ hit }) => {})   // also: click, legend-toggle, render

An element holds one chart: a new Chart on it replaces the one already there. The React, Vue and element wrappers call destroy() for you.

Theming

Everything visual is CSS. The stylesheet defines tokens on :root for light and dark, and every element in the SVG has a semantic class.

.revenue-chart {
  --tc-color-1: oklch(60% 0.2 250);   /* palette slots --tc-color-1 … 8 */
  --tc-stroke-width: 3px;
  --tc-font-size: 13px;
}
.revenue-chart .tc-series-2 .tc-line { stroke-dasharray: 4 4; }

Tokens include --tc-color-1 … --tc-color-8, --tc-surface, --tc-text-color, --tc-text-muted, --tc-grid-color, --tc-font-family, --tc-font-size, --tc-stroke-width, --tc-area-opacity, --tc-duration and the --tc-tooltip-* set (--tc-tooltip-light-* for the white variant).

Dark mode follows prefers-color-scheme; data-theme="dark" or "light" on any ancestor overrides it. Try the switch in the header.

The same chart with three CSS variables set on its container.

React, Vue, custom elements, Bootstrap

Each adapter is a package of its own; all of them need the core and its stylesheet.

React

npm install @tabler/charts @tabler/charts-react
import { LineChart } from '@tabler/charts-react'
import '@tabler/charts/style.css'

export function Revenue({ data }) {
  return <LineChart data={data} aspectRatio={3} onClick={({ hit }) => select(hit)} />
}

Vue

npm install @tabler/charts @tabler/charts-vue
<script setup>
import { LineChart } from '@tabler/charts-vue'
import '@tabler/charts/style.css'
const data = { labels: ['Mon', 'Tue', 'Wed'], series: [{ name: 'Visitors', values: [3, 5, 4] }] }
</script>

<template>
  <LineChart :data="data" :aspect-ratio="3" @click="({ hit }) => select(hit)" />
</template>

Both have a component per type (LineChart, BarChart …) and a generic TablerChart with a type prop. Props are the chart options, events are the chart events, and a ref gives the Chart instance.

Custom element

import { defineChartElement } from '@tabler/charts-elements'
import '@tabler/charts/style.css'

defineChartElement() // registers <tabler-chart>
<tabler-chart type="line" label="Visitors" aspect-ratio="3">
  <script type="application/json">
    { "labels": ["Mon", "Tue", "Wed"], "series": [{ "name": "Visitors", "values": [3, 5, 4] }] }
  </script>
</tabler-chart>

Bootstrap and Tabler

@tabler/charts-bootstrap maps the palette to the framework's theme colors and adds a data API, so a chart is a div with attributes.

import '@tabler/charts/style.css'
import '@tabler/charts-bootstrap/tabler.css' // or bootstrap.css
import { init } from '@tabler/charts-bootstrap'

await init() // every [data-tc-chart] on the page
<div data-tc-chart="line" data-tc-src="/api/sales.json" data-tc-aspect-ratio="3"></div>

Smaller bundles

@tabler/charts gives you Chart with every plugin and feature. @tabler/charts/core is a bare Chart: add only what you use.

import { Chart, highlight, tooltip } from '@tabler/charts/core'
import { line } from '@tabler/charts/line'
import '@tabler/charts/time' // only if you use x: { type: 'time' }

new Chart('#el', { type: line, data, plugins: [highlight(), tooltip()] })

Optional features register themselves when imported: /time, /log, /decimate, /annotations, /value-labels, /patterns, /hydrate, /export. A feature you use but did not import throws an error that names the import.

Server rendering

import { chartToString, line } from '@tabler/charts'

const svg = chartToString(
  { type: line, data, id: 'sales', locale: 'en-US', fontSize: 12 },
  { width: 600, height: 300 },
)

Put the SVG in the chart's container. A Chart created on the same element later takes the markup over node by node. Set id, locale and fontSize so the server and browser layouts match. The React and Vue components do this for you.

Export

import { downloadChart, exportImage, exportSVG } from '@tabler/charts'

const svg = exportSVG(chart)                        // standalone SVG string
const png = await exportImage(chart, { scale: 3 })  // Blob; also image/jpeg, image/webp
await downloadChart(chart, { format: 'svg' })       // saves "<title>.svg"

The export copies the computed styles into the SVG, so your theming comes along. Or let the chart offer it: download: true puts a small menu in the corner.

Accessibility

  • Every chart is a role="img" with an accessible name; title and description set them.
  • A data table is there for screen readers, hidden visually unless table: 'visible'.
  • Keyboard: Left and Right walk the categories, Up and Down the series, Home and End jump to the ends, Escape clears.
  • The default palette is checked for colorblind separation; patterns: true and shapes: true make series independent of color.
  • prefers-reduced-motion turns animations off; forced colors are supported.