Chart
Bar, line, area and other charts on TanStack Charts, with a visible title and description.
Installation
npx shadcn@latest add @oakoss/chartUsage
import { barY, defineChart } from '@tanstack/charts';
import { scaleBand } from '@tanstack/charts/scales/band';
import { scaleLinear } from '@tanstack/charts/scales/linear';
import { tooltip } from '@tanstack/charts/tooltip';
import { ChartContainer, ChartPlot } from '#/components/ui/data/chart';
import type { ChartConfig } from '#/hooks/use-chart';
const config = {
desktop: { color: 'var(--color-chart-1)', label: 'Desktop' },
mobile: { color: 'var(--color-chart-2)', label: 'Mobile' },
} satisfies ChartConfig;
const definition = defineChart({
marks: [barY(visitors, { color: 'device', x: 'month', y: 'visitors' })],
scales: {
x: { scale: scaleBand },
y: { grid: true, nice: true, scale: scaleLinear },
},
tooltip,
});
<ChartContainer
config={config}
description="Desktop and mobile visitors from January to June."
title="Visitors by month"
>
<ChartPlot definition={definition} />
</ChartContainer>;The chart itself is a TanStack Charts
definition: marks, scales, focus and the tooltip all live in it.
ChartContainer is the figure, with your title and description as its
caption, and ChartPlot renders the definition inside it, named by that
caption. Content you place in the container, such as a summary, sits in the
figure with the chart. Build the definition outside the component, or
memoize it on the values it captures: a new definition rebuilds the chart.
config names each series and category, and an entry with a color is a
series. Marks name a row's series with their color channel, and ChartPlot
turns the config into TanStack's color scale when the definition sets no
color, so the marks, tooltip and legend share one mapping. Charts with
several series take one row per value, so focus can group a month's values
into one tooltip:
const visitors = [
{ device: 'desktop', month: 'January', visitors: 186 },
{ device: 'mobile', month: 'January', visitors: 80 },
];A mark with no series takes the theme's --color-chart-1 to
--color-chart-5 in turn, five hues apart from the primary color that reach
3:1 on the page and stay distinct with color blindness. A sixth takes the
muted foreground gray, which suits an "Other" series but can match a hue
under color blindness, so label it. Past five, tell series apart with
dashes, markers or direct labels rather than more colors. When
color means something else, such as a status, the series comes from z
instead: the legend can then highlight it but not hide it.
Examples
Legend
ChartLegend lists the config's series, each a toggle that hides its series;
TanStack removes it without moving the axes. Hovering or focusing an item dims
the other series. The definition needs nothing for either: ChartPlot adds
the legend's colors, and dims each mark whose series comes from color
unless the mark sets states of its own.
<ChartContainer config={config} description="…" title="Visitors by month">
<ChartPlot definition={definition} />
<ChartLegend />
</ChartContainer>The container holds the hidden series. defaultHiddenSeries hides some at
first; pass hiddenSeries and onHiddenSeriesChange to keep them in your own
state, such as the URL. isStatic makes the legend a plain list, as it is
for a single series. The chart at the top of this page has a legend.
Data table
ChartTable shows the values each plot drew behind a "View as table"
button: a row per category, headed by categoryLabel, and a column per
series from the config. A series the legend hides leaves the table too. A
chart without series, such as one bar per browser, takes a row per point
and a valueLabel column; so does one where two marks draw the same series,
with a seriesLabel column, so no value is dropped. The chart at the top of
this page has one.
<ChartContainer config={config} description="…" title="Visitors by month">
<ChartPlot definition={definition} />
<ChartTable categoryLabel="Month" />
</ChartContainer>The table is built from what the chart drew, so it appears once the chart renders in the browser. A pie slice's point carries its angle, not its value, so give a pie chart a table of your own.
Focus on bars
Focus marks a line's point with a ring. On bars, an outline marks the
focused bar instead: give each bar mark chartBarStates, which also carries
the legend's highlight, and set focusRing: false so the ring's dot doesn't
sit on the bar's edge.
defineChart({
focusRing: false,
marks: [barY(visitors, { color: 'device', states: chartBarStates /* … */ })],
// …
});Loading, error and empty
status replaces the plot with a skeleton of its size ('loading'), an
alert ('error') or a "No data" message ('empty'), so the layout holds
when the data comes. fallback replaces what a status shows, for example with a
retry button. A plot that draws no points keeps its axes and says "No data"
over them, or "All series are hidden" when the legend hides every one.
loadingLabel, errorLabel, emptyLabel and hiddenLabel change the
text.
Line and crosshair
focus: 'group-x' shows every series at the focused x value in one tooltip,
and the crosshair mark draws a rule there. maxFocusDistance: Infinity
snaps to the nearest month wherever the pointer is.
Tooltip
The tooltip is ChartTooltipContent, rendered through ChartPlot's
renderTooltipBody. Render it yourself to change indicator (dot, line or dashed), hide
the heading or indicators, or format the heading and values. The definition
still needs TanStack's tooltip, which decides when it shows.
The heading is the value the focused points share, usually the x value, and
each row shows the other axis; a bar or area reports its length, and a range
its two ends. A pie slice's point carries its angle and radius, so pass
labelFormatter and valueFormatter that read the slice's data from
point.datum.
Axes and formatting
Axis titles are the axis label, and ticks.values picks which ticks show,
here only the first and last month. Numbers and dates format in the app's
locale, from React Aria's
I18nProvider: the tooltip, the
table and the ticks of a numeric axis that sets no format. Ticks keep every
decimal their values have, so an axis from 0.00001 to 0.00003 doesn't read
as a row of zeros. The container's format sets their number and date options
together, here a currency. A time axis keeps TanStack's labels, which pick the
unit each tick needs.
Accessibility
The chart is a figure named by its title and described by its
description, both visible in its caption, so the comparison it shows reads
before the graphic. Inside, TanStack renders an SVG with role img, the same
name and the description as its desc. Put the conclusion a reader should
draw, or the values that matter, in the description.
TanStack makes the chart one tab stop and moves a virtual focus between its
points, showing the tooltip for the focused one. The tooltip is a polite
live region, and it speaks what it shows: the series named from the config,
values in the app's locale. A chart without a tooltip announces the focused
points through a status region of its own. ChartTable gives the exact
values as a real table, for readers who need numbers rather than a picture.
Focus is marked on the point, not around the chart: a ring with the page's background inside and its foreground outside, or an outline on a bar, so it holds 3:1 on any series color. Hovering marks a point the same way. A chart with no points to mark keeps its outline. In forced colors the marker takes system colors, since SVG strokes keep their own colors there.
| Key | Action |
|---|---|
Tab | Focuses the chart, on its first point |
Arrow keys | Move to the next or previous point |
Home / End | Move to the first or last point |
Enter or Space | Pins the tooltip open |
Escape | Hides the tooltip until focus moves, or closes a pinned one |
An interactive legend is a
toolbar named by its
label ("Series"), one tab stop with arrow keys between its items. Each
item is a toggle button named by its series alone, with aria-pressed set
while the series shows; the
WAI-ARIA button pattern
keeps a toggle's name the same in both states. Focus highlights a series as
hover does, and a hidden series doesn't highlight. A hidden item's swatch is
hollow and its label struck through, so the state doesn't rest on color.
Swatches keep their series colors in forced colors, as the tooltip's
indicators do.
| Key | Action |
|---|---|
Tab | Moves into the legend, or on past it |
Arrow Left / Right | In the legend, moves between items |
Enter or Space | On a legend item, shows or hides its series |
API
ChartContainer
A figure with a caption, which hands config, title, description, the
number and date format, and the hidden series to the parts inside it.
Props
Prop
Type
Also accepts figure props, except the ARIA naming ones: the caption names
the figure.
Data attributes
| Attribute | Present when |
|---|---|
data-slot | Always: chart, and chart-caption, chart-title and chart-description in its caption |
ChartPlot
TanStack's
Chart,
named and described by the container's caption, with ChartTooltipContent
as its tooltip body. It accepts TanStack Chart's props, except ariaLabel,
ariaDescription and style; aspectRatio defaults to 16:9. Outside a
ChartContainer it throws.
It fills in what the definition leaves unset: the focus ring, the tooltip's
spoken text (unless the tooltip sets content, format, formatGroup or
items), the config's color scale with the legend's hidden series, the
legend's dimming on marks whose series comes from color and that set no
states, and a locale format on each numeric axis's ticks. It also adds
the legend's highlight control. A responsive definition gets the same in each
spec it builds.
Props
Prop
Type
Data attributes
| Attribute | Present when |
|---|---|
data-slot | Always: chart-plot, and chart-empty on the message over an empty plot |
data-status | Given status: loading, error or empty |
ChartTable
The plotted values in a Table, behind a Collapsible.
Props
Prop
Type
Data attributes
| Attribute | Present when |
|---|---|
data-slot | Always: chart-table |
ChartTooltipContent
The tooltip body, a div of one row per focused point.
Props
Prop
Type
Also takes the context renderTooltipBody passes.
Data attributes
| Attribute | Present when |
|---|---|
data-slot | Always: chart-tooltip, chart-tooltip-label, chart-tooltip-item and chart-tooltip-indicator |
ChartLegend
The config's series: a React Aria
ToggleButtonGroup of toggle
buttons, or a ul given isStatic or a single series.
Props
Prop
Type
Data attributes
| Attribute | Present when |
|---|---|
data-slot | Always: chart-legend, chart-legend-item on a toggle, chart-legend-swatch on each swatch |
data-selected | On a toggle whose series shows |
chartColor, chartSeriesStates and chartBarStates
ChartPlot fills in the first two; use them when a definition sets its own
color or states. A definition that sets its own color passes the
container's hidden series, useChart().hidden, so the legend hides its
series; otherwise give its legend isStatic. chartColor(config, hidden)
returns a definition's color option: the config's series as the color
domain, their colors as the
range, and a legend that draws nothing and removes the hidden series after
the scales resolve. chartSeriesStates goes in a mark's states and dims its
series while the legend highlights another. chartBarStates adds an outline
on the focused or hovered bar; use it on bar marks with focusRing: false.
useChartFormatter
Returns a function that formats a number or date in the app's locale, with
optional number and date format options, as the container's format does
for its parts. Dates format in UTC by default. The function changes only when
the locale or the options' values do, so options can be written inline.