Skip to main content

Bar Chart

A bar chart for comparing values across categories, with grouped and stacked variants. Compose the gridlines, axes, and one BarChart.Bar per series inside BarChart.Root.

When to use

  • Compare values across discrete categories: months, endpoints, plans.
  • Show time-binned totals, such as requests per day or cost per week. Each bar is one bucket's total, so the daily chart above is a bar chart.
  • Compare series side by side within each category with grouped bars, the default.
  • Show how parts make up each category's total with stacked bars.
  • Prefer LineChart for a trend over continuous time: samples at each timestamp read as a stream, not as buckets.
  • Prefer AreaChart for a total and its parts over continuous time.

Grouped bars

The default layout draws one bar per series side by side within each category: the head-to-head comparison. Always compose BarChart.Legend on multi-series charts: series identity must never rely on color-matching alone.

Stacked bars

Add stacked to the Root to stack the composed series instead of grouping them. Bars stack from the baseline up in registration order: series that mount together register in composition order, so the first BarChart.Bar sits on the baseline and the last on top. A Bar that mounts later stacks on top of every series already registered, whatever its position in the JSX, and a dataKey that unmounts and returns resumes its original position. Reordering the parts of a mounted chart does not restack it: the position sticks to the dataKey, which is what keeps a series from jumping when you rename its label. The tooltip leads with the column's total, then lists the far end of the stack first, so a vertical chart reads top-down and a horizontal one reads from the far end back to the baseline.

Sparse stacks

A stack whose series are zero on most columns is the shape a "usage by region" or "usage by access key" chart produces. Every geometry decision on a stacked bar is per column, not per series. A stack rounds both of its ends at 2px, so the rounded corners go to the segments that actually start and end that column. The 1px surface gap is carved only where a neighbor adjoins. March carries one series, so its one segment wears both rounded ends. June carries all three, so its seams are separated. Both orientations follow the same rule.

Segments smaller than the surface gap

A segment can be worth less than one pixel: a sub-cent line item against a dollar-scale axis. The gap carves at most half of a segment's painted extent, so a short segment paints shorter rather than inverting or vanishing, and a taller segment never paints shorter than the one beside it. A segment that rounds to no ink at all cannot take the rounded end from the segment a reader can see: March's events value is $0.004, so the column reads the same as May's exact $0.

Diverging stacks

Negative values pile downward from the zero baseline while positive values pile up, and each pile caps its own outer end. The axis grows below zero on its own: no yDomain override, because a bar chart's minimum is the baseline, not the data floor. April is the month worth looking at: 62 endpoints added against 112 lost, so the net is negative and the two piles are visibly unequal. Series that carry good or bad meaning wear the functional colors: success for the endpoints added, danger and warning for the two kinds of loss.

No usage yet

An all-zero series is data, not an empty state: it reports that nothing happened. The value axis stays anchored at the baseline, so the zero line sits on the axis instead of floating through the middle of the plot. Keep the accessible name, the tooltip, and the data table: a reader and a screen reader both need to hear "0", not nothing. Reach for mode="decorative" only when the values are a synthetic backdrop behind an empty-state message; see Decorative charts.

Regrouping a live chart

A dashboard that regroups one chart (by provider, then by region, then by access key) cycles a new set of dataKeys through the same Root. Each series names its own color, so keep the color with the series data: a series keeps its color when its siblings appear or disappear, and the same entity paints the same color in every chart.

Do not put a key on the Root. Remounting discards the tween state, the measured layout, and the hover position, and it replays the enter animation on every switch. Cycle the series instead and let the Root keep its store.

Brand colors

A chart of named things (AI model providers, cloud vendors, plan tiers) often wants each thing's own brand color, the same on every chart and every page. When no mantle color name fits, declare the values as custom properties on the Root and pass each one to the matching series as a CSS string. The chart resolves them inside the Root's own cascade. The legend swatch and the tooltip stroke emit the same var(), so one declaration set covers all three surfaces.

Use var(--your-token) rather than a raw hex. A hex freezes: the same value paints on white and on near-black. The dark theme cannot adjust it. A custom property lets you give each theme its own value, and the chart picks up the new value whenever the theme changes.

A brand color is outside mantle's measured tokens, so check it against the card in both themes and against the other colors on the chart. Series order decides whether a close pair bites, because a stacked chart only puts consecutive series against each other. The example runs OpenAI, Claude, Gemini: under simulated color vision deficiency (CVD), Claude's orange sits close to OpenAI's green, so Claude wears a texture. When a pair does collide, reorder the series, change the color, or add a texture.

Brand colors have three more limits:

  • Grouped bars compare every series to every other, not only its neighbors.
  • Brand colors collide with each other. Five of the major AI providers use nearly the same blue.
  • A black or near-black brand color carries no hue, so it reads as the neutral Other series.

A named entity that has no brand color takes a mantle color name, as Acme LLM and BYO Router do above. Pick names that stay clear of the brand hues on the same chart.

Horizontal bars

orientation names the direction the bars point, not an axis: "vertical" (the default) bars stand up, "horizontal" bars lie across. Set orientation="horizontal" to grow bars rightward from a left baseline with categories banded down the y axis. Reach for it when category labels are long (they read straight instead of angled or truncated under the axis) or when there are many categories to rank. xKey still names the category and YAxis still labels the value. Only the drawing flips: the category axis moves to the left gutter, the value axis to the bottom, and the baseline, reference lines, and the two rung textures ("perpendicular" and "parallel") all rotate to match. The "grid" lattice inks both rung directions, so it looks the same either way. Everything else (grouping, stacking, hover, the data table) works unchanged. The keyboard follows the layout: the Down and Up arrow keys step through the categories, and Page Down and Page Up jump forward and back. The Left and Right arrow keys still work.

Textures

When a multi-series or stacked chart can't rely on color alone (color-vision deficiencies, grayscale print and exports, forced-colors mode), give each series a fill texture. Textures are a redundant identity encoding alongside color: "hatch" (diagonal lines at 45°), "hatch-reverse" (its 135° mirror), "crosshatch" (both), "perpendicular" (rungs across the bar's length: horizontal lines on vertical bars), "parallel" (rungs along it: vertical lines on vertical bars), "grid" (both rung directions crossed), and "dots" (an offset dot field). The two rung textures flip with orientation, in opposite senses. Every other value draws the same whichever way the bars point, "grid" included: it is the orthogonal lattice against "crosshatch"'s diagonal one.

A textured series paints a light tint of its color (25% of the color mixed into the card surface) and draws the pattern's marks in the full color. A solid series and a textured series of one color therefore read as a pair: the dark member and the light member. Every legend key wears its series' pattern, so the mapping never depends on hue.

Texture is opt-in and purposeful, never decorative. Mantle assigns none of it for you. A bar carries no point shape, so the texture you set is a bar's only second channel. Keep solid fills when color alone already carries identity. When it does not, either leave the first series solid and texture the rest, or texture only the series in the pair that collides. The Diverging stacks and Brand colors examples above take the targeted form.

Sharing one color

Several series can share one color and stay apart by texture. Reach for it when the series belong to one thing: zones of a region, shards of a cluster, tiers of one plan, or the In and Out traffic of one agent. The shared color reads as the family. Series that share no family belong in one "Other" series instead.

Two rules make it work:

  • Every member sets the same color. The color names the family, not the member.
  • Every member carries its own texture. Two series that share a color and a texture paint identically. Nothing warns you. One member may stay solid; the rest take a value each.

Count the costs before you reach for it. One hue no longer names one series, so the legend carries the mapping, and every member needs a label. A pair is the clearest form: an Out series with color="neutral" beside an In series with color="neutral" and texture="hatch" reads as the dark and light halves of one agent's traffic. Neutral bars in a card list shows the pair.

Below, the three us-east zones share blue, and eu-west-1 takes its own color.

Neutral bars in a card list

Use color="neutral" when a chart gives context to a card and is not its subject. On the dashboard's Agents page, each agent card shows the last hour of throughput beside the agent's name. Out sits on the baseline with color="neutral". In sits on top with color="neutral" and texture="hatch". One color names the agent's traffic, and the texture tells the two directions apart.

A chart with no axes and no grid has no plot padding and no zero rule, and the tallest stack leaves 12% headroom. The tooltip leads with the bucket's total. The cards share one live region through BarChart.List.

Single series

A single-series chart draws every bar in the one color its BarChart.Bar names. One series means one color: never color bars by their own value, and never assign each category its own hue; that adds a false second encoding to data the bar lengths already show. There is no legend either; BarChart.Legend renders nothing for a single series because the chart's title already names it. Here the visible title carries the accessible name via aria-labelledby.

Integer counts

Counts are integers, and the value axis knows it: when every series value is a whole number, ticks step by whole numbers. This chart's [0, 3] domain ticks at 0, 1, 2, 3 rather than inventing a meaningless "1.5 failures" gridline. Nothing to configure; the behavior follows the data, so a single fractional value (an average, a rate) restores sub-integer ticks. The same guarantee covers the value axis of horizontal bars and linear x axes on the other chart families.

Reference lines

Compose BarChart.ReferenceLine to mark a threshold, budget, or limit as a dashed horizontal line at a y value, with an optional label painted above its right end.

Custom tooltip

The tooltip is part of BarChart.Root's interaction contract and is always on: composing BarChart.Tooltip never adds or removes it, it only customizes the readout. Use labelFormat and valueFormat to format the rows, footer to append a hint below them, or the render-prop children to replace the content entirely.

Activation

onDatumActivate fires when a user clicks a bar with the primary button, or presses Enter or Space while a category is active. The event carries { index, xValue, datum, dataKey }. On a stacked chart, dataKey names the segment the pointer sits in; otherwise it names the series nearest the pointer. Keyboard and whole-band activation set it to null. Click a bar (or Tab to the chart, arrow to a month, and press Enter) to update the readout below.

Activating a stacked segment

On a stacked chart dataKey names the segment the pointer sits in, never the boundary it sits near, because the mark is the filled span. Click the lower third of a band and the readout still names that band. Resolving by the nearest cumulative boundary instead would hand the baseline-side half of every segment to the series below it.

Controlled hover

Pass activeIndex with onActiveIndexChange to control the active category from outside the chart: pin a category from a linked table row, or sync hover across sibling charts. Omit activeIndex for uncontrolled hover.

Pending data

Set pending while a refetch is in flight: the chart holds the previous frame at reduced opacity instead of unmounting. Never swap a chart that has rendered once for a skeleton: the held frame keeps the axes, scales, and the user's place stable while fresh data loads.

Live data

Live values on a bar chart update in place: the categories are fixed, so bars never scroll. Each update morphs every bar from its current height to its new value with a per-datum tween, while the y axis glides to fit: the domain continuously chases its target and the value tick labels fade between tick sets instead of popping. prefers-reduced-motion snaps every update instantly. When the live dimension is time (a sliding window of appends), reach for a LineChart or AreaChart instead: bars at every timestamp read as categories, not a stream.

When the categories change (a sliding window of buckets, for example), the bars snap to their new values, and the y axis still glides. Motion plays only while the chart is on screen. A chart that is near the viewport but off screen paints each update settled, with no tween.

This demo recomputes all six regions every 400ms from a pure function of a tick counter (offset sine waves per region), so it renders deterministically; a real chart would replace data as new readings arrive.

Copy as markdown

BarChart.CopyButton copies the chart's current rows to the clipboard as a machine-stable, GitHub-flavored markdown table: the category column plus one column per series in paint order (plain un-separated numbers, an em dash for gaps). The table pastes into Slack, issues, spreadsheets, and LLM chats. The button renders in flow where composed; Root is relatively positioned, so className can dock it over a corner.

Lists of charts

A page of 100 charts pays for the handful a reader can see. A dormant BarChart.Root is a shell: the plot box, the named interaction overlay, and its screen-reader description. It holds no paint surface and no engine until it comes within one viewport of the visible area, takes focus, or prints; then it activates outside React, in slices of a few milliseconds that yield between them, on-screen charts first, and paints in the task that activates it. A print paints every chart settled, with tick labels and gridlines at full opacity. The hover layers and the tooltip surface mount on the first hover, and the screen-reader data table waits for focus alone: it mounts once a reader tabs into the chart, so a page of sparklines holds no hidden tables until a reader asks for one. Add content-visibility: auto to your list's cards as a complement: it skips style and layout for offscreen cards, and the chart's own gate already skips paint.

Wrap a list of interactive charts in BarChart.List. The charts inside share one role="status" live region, so a page of 100 charts mounts one region instead of one per chart, plus one for each BarChart.CopyButton. Each chart keeps its own tooltip, description, and data table. Charts of different families can share one List, so one BarChart.List can hold a grid of bar, line, area, and scatter charts. A static chart has no tooltip and no live region, so a list of sparklines needs no List.

The mount cost of a list is measured, not assumed. The chart mount benchmark renders a DataTable of 100 rows with two sparklines each; mode=list renders cards of full charts, and n, kind, and points set the shape. The Playwright driver in apps/www/bench/ loads the page and reports main-thread time, long tasks, and frames per case.

Modes

mode sets how much of the chart's contract a Root exposes. Pick by what a reader does with the chart.

modeUse it forA reader gets
"interactive" (default)A chart a reader explores: a dashboard panel, a detail page, a report with a question behind it.A named role="application" Tab stop, hover and keyboard point cursor, a tooltip readout, polite announcements, and an sr-only data table on focus.
"static"A chart a reader glances at while the exact values sit beside it: a sparkline in a table row or a card, a trend in a print report.A named role="img" with a text description (kind, count, range, series), no Tab stop, no hover, no tooltip, no table. animate defaults to false.
"decorative"A placeholder whose values are not information: synthetic bars behind an empty state, a hero backdrop.Nothing: hidden from assistive technology, out of the tab order, inert, every series in one neutral fill.

Noninteractive is not decorative. A sparkline beside a total still tells a reader when activity happened and how it varied, so it keeps a name and a description; only its values live in the text beside it. One hundred sparklines in a table as one hundred Tab stops is a focus order no reader wants, and a readout that only a pointer can reach fails WCAG 2.2 SC 2.1.1 (Keyboard), so "static" offers neither. A chart that is the only source of its values stays "interactive".

Static charts

Set mode="static" for a chart a reader glances at while the exact values sit beside it. The plot is a named role="img": it takes the same aria-label or aria-labelledby an interactive chart does, and its aria-describedby points at the description, so a screen reader hears the chart kind, the category count, the first and last category, and the series labels without a Tab stop. There is no interaction overlay: no hover band, no tooltip, no keyboard point cursor, no data table, and no live region, and a composed BarChart.Tooltip has no effect. Pointer events pass through to the row or card behind it. The series keep their colors. animate defaults to false, because a list of sparklines that each play a reveal as the reader scrolls is motion with no information in it; pass animate to play the reveal. The interaction props (activeIndex, onActiveIndexChange, onDatumActivate) are forbidden at the type level. The Sparklines in a List recipe is the worked example.

<div className="flex items-center gap-2">	<BarChart.Root		data={service.requests}		xKey="day"		mode="static"		aria-label={`Requests for ${service.name}, last 30 days`}		className="aspect-auto h-6 w-28"	>		<BarChart.Bar dataKey="count" label="Requests" color="blue" />	</BarChart.Root>	<span className="text-muted text-xs tabular-nums">{compact(service.requestTotal)}</span></div>

Decorative charts

Set mode="decorative" to render the chart as a placeholder backdrop instead of real data: synthetic bars behind an empty state, an atmospheric hero graphic. A decorative chart keeps its visual rendering and animation but drops every layer that only makes sense for real data: it is hidden from assistive technology, removed from the tab order, and inert to pointer and keyboard, with no hover band, tooltip, sr-only data table, or live region. Because the values aren't information, mode="decorative" is mutually exclusive with the accessible-name props (aria-label / aria-labelledby) and the interaction props (activeIndex, onActiveIndexChange, onDatumActivate); the type won't compile with both.

A decorative chart also drops the series colors. Every series paints --color-chart-decorative, one neutral fill that outranks a series' color. A backdrop carries no series identity, and a hue on values that are not information invites a reader to decode it.

That fill is what keeps an overlaid message readable. Empty.Description sits on text-muted, which measures 4.88:1 on a bare light card (0.38 over the 4.5:1 floor for 14px text), so any tint under that copy spends the headroom. --color-chart-decorative is the darkest neutral step that still clears the floor in both themes: 4.56:1 in light and 4.93:1 in dark. The message needs no scrim behind it, no dimming, and no blur. Redeclare the token on the Root to retune the fill (className="[--color-chart-decorative:var(--color-neutral-100)]") and re-measure the copy against the value you pick.

Reach for mode="decorative" over hand-rolled inert + CSS: it removes the interaction overlay at the source, so consumers never target chart internals to neutralize it. Keep the real empty-state message as a sibling of the chart (not inside it) so screen readers still announce it; the decorative chart itself is silent.

mode="decorative" says the values are not information; it is not a disabled flag (a chart is not a form control). For real data a reader only glances at, use mode="static".

Composition

Compose the parts of a BarChart together to build your own:

BarChart.Root├── BarChart.Grid├── BarChart.XAxis├── BarChart.YAxis├── BarChart.Bar (one per series)├── BarChart.ReferenceLine├── BarChart.Tooltip├── BarChart.Legend└── BarChart.CopyButton

The interaction layer ships with Root, and there is no part to add for it: the per-category hover band and tooltip, keyboard stepping, polite announcements, and an sr-only description. The sr-only data table mounts once the chart takes focus.

Wrap a list of Roots in BarChart.List so they share one live region:

BarChart.List└── BarChart.Root (one per chart)

Axes and density

Bars encode value by length from a shared zero baseline. The y axis therefore always starts at 0, and a truncated bar is not possible.

Density takes care of itself. The chart at the top of this page plots 91 daily bars. The band axis thins its own labels: it spaces them evenly from the first day, and it skips a label instead of rotating it when two collide. Date x values format as dates in the tooltip, land as exact ISO timestamps in the data-table twin, and take a tickFormat for short axis labels.

Color and accessibility

Design the chart to look right first. Then get as close to accessible as you can, and say plainly where a choice falls short. A chart that follows every contrast rule to the letter can turn noisy, so mantle documents the guidance and its exemptions and forbids no color. This section is the reference for every chart family: bar, line, area, and scatter.

What WCAG asks of a chart

WCAG 2.2 SC 1.4.11 Non-text Contrast asks for 3:1 against adjacent colors for the "parts of graphics required to understand the content". Bars, slices, lines, and points are those parts. Text has its own rule (SC 1.4.3, 4.5:1).

  • A mark needs 3:1 against the surface behind it.
  • Lines need 3:1 against their background. They "do not need to contrast with each other or the graduated lines", so two lines of close colors pass if each one clears the background.

Two things exempt a mark, because they make it no longer required to understand the content:

  • The same values in another form a sighted reader can see: text labels on or beside the marks, or a table the reader can open. W3C's example is a table that shows when the reader presses a "Long Description" button.
  • A darker border around a low-contrast mark. W3C's pie chart example adds "a darker border … around the yellow slice".

Two things do not exempt a mark:

  • A hover tooltip. "The unfocused default version must already have sufficiently contrasting colors or text."
  • Mantle's own data table. The tooltip and the sr-only data table carry every value, but the table is for screen readers. A sighted reader with low vision never sees it, so it does not exempt the marks.

What mantle measures

Each color name paints its --color-chart-<name> token: the color's 600 step in light mode and its 500 step in dark mode (the 500 step reads washed out on white). Mantle measures every name against the card surface in both themes, in chart/tokens.test.ts:

ThemeNames under 3:1 on the card
lightyellow (2.94:1)
darknone

The color choices are yours. Mantle does not promise that any set of names stays apart for a reader with a color vision deficiency. Two habits help:

  • Pick colors that differ in lightness as well as hue. Blue beside emerald differs mostly in hue; blue beside amber differs in lightness too.
  • Add a second encoding when series sit side by side: texture on bars, shape on points.

Keep a chart to eight series

A legend of a dozen access keys is a list no reader can match to the bars, and each added color sits closer to one already on the chart. Rank the series by the window's total, keep the top seven, and sum the rest into one "Other" series:

const TOP_N = 7; /** The top-N keys by window total, with every other key summed into "Other". */function foldTail(rows, keys) {	const totals = keys.map((key) => ({		key,		total: rows.reduce((sum, row) => sum + (row[key] ?? 0), 0),	}));	const top = totals		.toSorted((a, b) => b.total - a.total)		.slice(0, TOP_N)		.map(({ key }) => key);	const tail = keys.filter((key) => !top.includes(key));	const folded = rows.map((row) => ({		...row,		other: tail.reduce((sum, key) => sum + (row[key] ?? 0), 0),	}));	return { rows: folded, series: tail.length === 0 ? top : [...top, "other"] };}

Give the Other series color="neutral", so it reads as the tail and not as one more series. Other is always neutral. Keep it last, so it sits at the far end of a stack. When several series belong to one thing, they can share one color and stay apart by texture; see Sharing one color.

When a color falls short

yellow in light mode sits under 3:1, and so can a brand color you pass as a CSS string. If a chart needs one of them, use one or more of these:

  • Put the color on a fill, not a thin line. A bar or a stacked segment is easier to see than a 2px line at the same contrast.
  • Show the values as visible text beside the marks: a total, a label, or a DataTable the reader can open. Visible values exempt the marks.
  • Add a texture (bars) or a shape (points), so the reader does not need the color to tell that series from the others.

Accessibility

Every interactive chart must have an accessible name: either a direct aria-label or an aria-labelledby reference to a visible title. This is enforced at the type level: BarChart.Root does not compile without exactly one of the two. Prefer aria-labelledby when the chart sits under a visible heading, so the name never drifts from the title. The name lands on the focusable interaction overlay, the chart's single named element (the paint surface itself is hidden from assistive technology, so the chart is never announced twice). A static chart names its plot role="img" instead and has no Tab stop. A decorative chart carries no real data, so it takes no accessible name and is hidden from assistive technology entirely.

The chart is a single Tab stop with a full keyboard model:

  • Left / Right arrows step between categories. On a horizontal chart, Down / Up arrows step too.
  • PageUp / PageDown jump forward and back in larger strides (about a tenth of the data). On a horizontal chart, PageDown jumps forward and PageUp jumps back.
  • Home / End jump to the first and last category.
  • Escape clears the active category.
  • Enter / Space activate the current category (fires onDatumActivate). A held key activates once.

Escape, Enter, and Space act only while a category is active. An idle Escape therefore reaches the surface around the chart, such as a panel that closes on Escape. A chord with Alt, Ctrl, or Meta passes through to the browser. In forced-colors mode, the focused chart shows a focus outline, and the hover band stays visible.

Keyboard stepping announces the category and each series' value through a debounced aria-live="polite" region, so rapid arrowing doesn't flood the screen-reader queue. Announcements follow keyboard steps only: the chart doesn't announce a data update while the keyboard cursor rests on a category. When the labelFormat or valueFormat of a composed BarChart.Tooltip returns a string or a number, the announcement uses it. A stacked chart announces the Total before the series values. The data table keeps the default number format.

The overlay's aria-describedby points at a screen-reader description, data-slot="bar-chart-description", so a screen reader hears what the chart holds when it takes focus: the chart kind, the number of categories, the first and last category, the series labels, and the keyboard instructions. For example: "Bar chart with 12 categories from Jan to Dec. Series: Desktop, Mobile. Use the left and right arrow keys to move between data points, …". An empty chart reads "Bar chart with no data." in place of the count and range. Server HTML carries the plain count alone. The range waits for hydration, because Intl output differs by locale, and the series labels register in layout effects, so both render on the client.

BarChart.Root mounts dormant and renders its sr-only data table (the category column plus one column per series) once it engages: once focus lands inside it (the overlay is the Tab stop, and a focusable part composed inside the Root, such as BarChart.CopyButton, counts too). It never goes dormant again. Visibility paints the chart but never mounts the table. The table is bounded to the first 150 rows, with a caption stating the summarization when the data is longer. The Root stamps data-state="dormant", then data-state="engaged", and the table mounts with the flip, so a screen reader's table list names only the charts the reader has focused. The description above names what every chart holds, focused or not. Tooltips enhance, they never gate, and no part removal can strip keyboard access to the data. The keyboard point cursor steps one category at a time, so it reaches every category. When the chart holds 4 or more categories per device pixel of plot width, each arrow key press moves one device-pixel column. The cursor then reaches one category per column. The table holds the first 150 rows, and BarChart.CopyButton copies every row.

The table doubles as the chart's machine-readable surface: value cells carry the raw number in data-value (and date row headers, where present, the exact ISO timestamp in <time dateTime>), so agents and scrapers read precise data from the DOM without reverse-engineering locale formatting. Assistive tech still hears the human-formatted text, and the table itself is addressable at data-slot="bar-chart-data-table". To reach it, an agent focuses the chart (a scroll into view is not enough), then waits for data-state="engaged" on the Root. BarChart.CopyButton hands over the same rows as markdown with neither step.

Accessibility limits

Every chart family (bar, line, area, and scatter) has these limits:

  • A live chart has no pause control. Add one to the page: WCAG 2.2 SC 2.2.2 (Pause, Stop, Hide) asks for a way to pause, stop, or hide content that updates by itself.
  • Point aria-labelledby at the title element, not at a container that holds the chart. A container's text includes the chart's own description and data table, so the name would repeat them.
  • When you set pending, announce the refresh yourself. The chart dims the plot and tells assistive technology nothing.
  • On a touch screen, a tap shows the readout only while the finger is down, and the same tap fires onDatumActivate.
  • A BarChart.CopyButton and a legend that scrolls each add one Tab stop.
  • Inside a mantle Dialog or Sheet, Escape closes the dialog even when a readout is open.
  • Escape dismisses the readout only while the chart's overlay has focus. A readout that a pointer hover alone opened stays until the pointer leaves.
  • The 3D rotation of a ScatterPlot is pointer-only and needs a drag.

API Reference

BarChart.Bar, BarChart.Grid, BarChart.XAxis, BarChart.YAxis, and BarChart.ReferenceLine are renderless: they register configuration with the Root, which paints everything on one surface: an <svg>. They accept no className or other DOM props. BarChart.Tooltip and BarChart.Legend accept div props: the tooltip forwards them to the readout element the Root owns, and the legend renders real DOM in flow below the plot. BarChart.CopyButton also renders real DOM: an icon button that accepts button props. BarChart.List renders a div around a list of Roots.

BarChart.Root

The root of a bar chart: owns the data, the scales, the renderer, and the entire interaction contract. Renders a <div> sized aspect-video at full width by default. Override the size with className. Bars encode value by length from a shared zero baseline, so the y domain minimum is fixed at 0.

All props from div, plus:

PropTypeDefaultDescription
datareadonly TDatum[]Rows of data; each BarChart.Bar reads one numeric key per row. Missing keys and null values render as gaps.
xKeyExtract<keyof TDatum, string>The key of each row's category (x) value.
aria-labelstringThe chart's accessible name. Exactly one of aria-label or aria-labelledby is required, enforced at the type level. Required unless mode is \"decorative\", which forbids it.
aria-labelledbystringID of a visible title element that names the chart. Preferred when the chart sits under a heading, so no duplicated text can drift. Required unless mode is \"decorative\", which forbids it.
mode?"interactive" | "static" | "decorative""interactive"How much of the contract the Root exposes: explore it ("interactive"), glance at it with its values beside it ("static": a named role="img", no Tab stop, no tooltip, no table, animate off by default), or paint a placeholder ("decorative": hidden from assistive technology, one neutral fill). The name props are required unless decorative, and the interaction props are allowed only when interactive. See Modes.
yDomain?[0, number | "auto"][0, "auto"]Override the automatic y maximum. The minimum is always the zero baseline.
stacked?booleanfalseStack the series from the baseline up in registration order. See Stacked bars.
orientation?"vertical" | "horizontal""vertical"The direction the bars point (not an axis): "vertical" bars stand up from a bottom baseline (categories along x); "horizontal" bars run rightward from a left baseline (categories down y). See Horizontal bars.
animate?booleantrueAnimate enter/update transitions; the enter transition plays when the chart first comes into view. prefers-reduced-motion always wins.
pending?booleanfalseHold the previous render at reduced opacity while fresh data loads. Never swap a chart that has rendered once for a skeleton.
activeIndex?number | nullControlled active datum index (null = none). Omit for uncontrolled hover. Allowed only when mode is "interactive".
onActiveIndexChange?(index: number | null) => voidNotified when hover/keyboard moves the active index. Allowed only when mode is "interactive".
onDatumActivate?(event: ChartDatumEvent) => voidNotified on datum activation: bar click, or Enter/Space on the focused chart. The event carries { index, xValue, datum, dataKey }; dataKey is the stacked segment the pointer sits in, else the series nearest the pointer, and null for keyboard/whole-band activation. Allowed only when mode is "interactive".

Data attributes

Data AttributeValueDescription
data-slot"bar-chart"The Root wrapper, with any forwarded chain ahead of it.
data-slot"bar-chart-plot"The plot box. Every overlay layer positions against it, and the resize observer measures it.
data-slot"bar-chart-svg"The <svg> the marks paint on. Always aria-hidden. Engine-owned: it is absent from server HTML and from a dormant chart, and the Root inserts it when the chart activates (near the viewport, on focus, or before print).
data-slot"bar-chart-crosshair"The vertical hairline; a bar chart never shows it. Engine-owned: it is absent from server HTML. The engine appends it on the first hover, keyboard step, or controlled activeIndex that names a datum. It stays until the Root destroys the engine, such as when mode leaves "interactive". Interactive charts only: a static or decorative chart inserts the surface alone.
data-slot"bar-chart-hover-band"The highlight behind the active category, one category wide. The engine writes its geometry as an inline style. Engine-owned: it is absent from server HTML. The engine appends it on the first hover, keyboard step, or controlled activeIndex that names a datum. It stays until the Root destroys the engine, such as when mode leaves "interactive". Interactive charts only: a static or decorative chart inserts the surface alone.
data-slot"bar-chart-markers"The container for the per-series hover dots; a bar chart never fills it. Engine-owned: it is absent from server HTML. The engine appends it on the first hover, keyboard step, or controlled activeIndex that names a datum. It stays until the Root destroys the engine, such as when mode leaves "interactive". Interactive charts only: a static or decorative chart inserts the surface alone.
data-slot"bar-chart-tooltip"The tooltip surface. The Root renders it on the first hover or keyboard step and keeps it; BarChart.Tooltip configures it. A chart nobody points at holds none.
data-slot"bar-chart-description"The sr-only description the overlay's aria-describedby points at: the chart kind, the category count, the first and last category, the series labels, and, on an interactive chart, the keyboard instructions. Omitted when mode="decorative".
data-slot"bar-chart-data-table"The sr-only data table. Mounts once focus lands inside the chart (data-state flips to "engaged") and stays. Interactive charts only.
data-state"dormant" | "engaged"On the Root. Flips to "engaged" once focus lands inside the chart, and never flips back. The data table mounts with it. Visibility paints the chart but never flips it. Interactive charts only.

BarChart.Bar

One bar series. Renders nothing itself: it registers the series with the chart, which paints it. Compose one Bar per series; with stacked on the Root, bars stack from the baseline up in registration order. Accepts no className or DOM props.

Bar thickness follows the category spacing; there is no barSize prop. Bars fill their category step except for a fixed 2px gap between neighbors. As steps narrow, the gap drops to 1px, then to none. On a wide step, a cap holds: a bar fills its slot up to 60% of one category's step, floored at 24px and ceilinged at 64px. Few categories therefore grow the bars rather than the air between them: seven days across a 93px step paint ~56px bars, not 24px bars in 69px of air. Grouped series split the band and each bar fills its own slot, so a group tightens instead of outgrowing its category. The rule reads the step alone, so the same data at the same width always paints the same pixels, and thickness only ever rises as categories thin out.

A bar, or a whole stack, rounds both of its ends at 2px. Stacked segments sit 1px apart. A chart with no axis and no grid runs its bars edge to edge, with 12% headroom over the tallest bar and no zero rule, so it reads as a sparkline.

PropTypeDefaultDescription
dataKeystringThe row key this series reads its numeric values from.
colorSeriesColorThe color the series paints: a mantle color name (the same Color that Badge takes), or any CSS color. Required. Prefer a per-theme var(--token) over a raw hex. See Chart color tokens and Color and accessibility.
label?stringdataKeyDisplay name for the legend, tooltip, and data table.
texture?"solid" | "hatch" | "hatch-reverse" | "crosshatch" | "perpendicular" | "parallel" | "grid" | "dots""solid"The fill texture the bars and their legend key wear: a light tint of the series color under marks in the full color. A redundant identity encoding alongside color. See Textures.

BarChart.Grid

Hairline value gridlines behind the bars (renderless; the chart paints it). The default runs perpendicular to the bars: horizontal lines for vertical bars, vertical lines for horizontal bars. Pass lines to force a direction. Omit the part to omit the grid. Accepts no className or DOM props.

PropTypeDefaultDescription
lines?"horizontal" | "vertical" | "both"perpendicular to the barsWhich gridlines to draw.

BarChart.XAxis

Category labels for the bars (renderless; the chart paints it): along the bottom for vertical bars, down the left gutter for horizontal bars. Labels that would collide are skipped, never rotated. Accepts no className or DOM props.

PropTypeDefaultDescription
tickFormat?(value: string | number | Date, context: { defaultLabel: string }) => stringFormat a tick label. Receives the row's category value. The second argument is { defaultLabel }: the label the axis paints without a formatter.
tickCount?numberTarget tick count (continuous scales only). Bar charts use a band scale, where label density is automatic: colliding labels are skipped.

BarChart.YAxis

Value tick labels (renderless; the chart paints it): along the left for vertical bars, across the bottom for horizontal bars. Ticks land on clean thousands-separated numbers. Accepts no className or DOM props.

PropTypeDefaultDescription
tickFormat?(value: number, context: { defaultLabel: string; step: number }) => stringthousands-separated numbersFormat a tick label. The second argument carries the tick step and the defaultLabel the axis paints without a formatter, so a formatter can add a unit to defaultLabel and keep its precision.
tickCount?numberMaximum tick count. When omitted, the axis aims for about 5 ticks. The axis can render fewer: ticks land on human-friendly steps, a vertical axis keeps about 28px for each tick, and a label that would overlap its neighbor is skipped. Integer-valued data never renders fractional ticks.

BarChart.ReferenceLine

A dashed marker at the value y, such as an SLO threshold, a budget, or a limit (renderless; the chart paints it). It crosses the value axis: a horizontal line for vertical bars, a vertical line for horizontal bars. Accepts no className or DOM props.

PropTypeDefaultDescription
ynumberThe y value the line marks.
label?stringA short label painted above the line's right end.
color?SeriesColorneutral reference colorLine color.

BarChart.Tooltip

Customizes the hover/keyboard tooltip readout. The tooltip itself is part of BarChart.Root's interaction contract and renders even when this part is absent. Compose it to format the label or values, append a footer, or replace the content entirely.

A children readout renders inside a <div data-slot="bar-chart-tooltip-label">. When it goes away, React removes that div instead of your own text nodes: a browser translation engine reparents text nodes, and a removal aimed at one throws. The div is display: contents, so it adds no box and your content stays a direct layout child of the parent. To style it as a box, set a display of your own on it first. Browser translation covers the mechanism and the rules your own components need.

The HoverSnapshot passed to footer and children describes the active category: { index, xValue, datum, points, viaKeyboard }, where points lists every series' value at the active index. Stacked, the rows run from the far end of the pile back to the baseline; unstacked, they follow registration order.

All props from div (forwarded to the tooltip element the Root owns) except children, plus:

PropTypeDefaultDescription
labelFormat?(value: string | number | Date) => ReactNodeFormat the x/label row of the readout.
valueFormat?(value: number, dataKey: string) => ReactNodeFormat each series value.
indicator?"line" | "none""line"The per-series color key: a short stroke (default) or nothing.
footer?ReactNode | ((snapshot: HoverSnapshot) => ReactNode)Extra content appended below the series rows (e.g. a "view logs" hint).
children?(snapshot: HoverSnapshot) => ReactNodeReplace the entire readout.

Data attributes

Data AttributeValueDescription
data-slot"bar-chart-tooltip-label"On the <div> wrapping a children readout. The default readout has none.

BarChart.Legend

The legend: series names keyed by color swatches, rendered as real DOM in flow below the plot. Always compose it on multi-series charts: identity must never rely on color-matching alone. It renders nothing for a single series (the chart's title already names it). The legend is at most 64px tall (max-h-16) and scrolls past that, so many series never take the plot's height in a fixed-height Root. Set a max-h-* class in className to change the bound.

A children render prop renders inside a <div data-slot="bar-chart-legend-label">. When it goes away, React removes that div instead of your own text nodes: a browser translation engine reparents text nodes, and a removal aimed at one throws. The div is display: contents, so it adds no box and your content stays a direct layout child of the parent. To style it as a box, set a display of your own on it first. Browser translation covers the mechanism and the rules your own components need.

All props from div except children, plus:

PropTypeDefaultDescription
children?(series: SeriesMeta[]) => ReactNodeReplace the default legend items; receives the registered series.

Data attributes

Data AttributeValueDescription
data-slot"bar-chart-legend"The legend list. BarChart.Legend renders it in flow below the plot.
data-slot"bar-chart-legend-label"On the <div> wrapping a children render prop. The default legend has none.
data-texture"solid" | "hatch" | "hatch-reverse" | "crosshatch" | "perpendicular" | "parallel" | "grid" | "dots"On each series' swatch, naming the texture its BarChart.Bar registered. The swatch paints the pattern itself, so target this only to restyle a key.

BarChart.CopyButton

A button that copies the chart's current data to the clipboard as a GitHub-flavored markdown table: the category column plus one column per series in paint order. Values are machine-stable (plain un-separated numbers, an em dash for gaps), so the paste target receives parseable data, not locale formatting. Renders an icon button in flow where composed; Root is relatively positioned, so className can dock it over a corner (e.g. absolute right-0 top-0).

All props from button, plus:

PropTypeDefaultDescription
label?string"Copy data as Markdown"The accessible name, rendered as the button's aria-label.
onCopy?(value: string) => voidCallback fired after a successful copy, passes the serialized markdown.
onCopyError?(error: unknown) => voidCallback fired when an error occurs during copying.
asChild?booleanfalseCompose the copy behavior onto your own element instead of the default button.

While a copy is fresh, an always-mounted role="status" element beside the button announces "Copied" to a screen reader.

Data AttributeValueDescription
data-slot"bar-chart-copy-button"The button the part renders.

BarChart.List

Groups a list of charts, such as one chart per card, so they share one role="status" live region. A page of 100 charts mounts one region instead of one per chart, plus one for each BarChart.CopyButton. Each chart keeps its own tooltip, description, and data table. Charts of different families can share one List. See Lists of charts.

Renders a div (bar-chart-list) that holds the charts in a display: contents wrapper (bar-chart-list-items), so a grid or flex layout on the List reaches the cards, and the live region as its last child. BarChart.List takes no asChild: a list element such as ul cannot hold the live region as a child.

All props from div.

Data AttributeValueDescription
data-slot"bar-chart-list"The List wrapper, with any forwarded chain ahead of it. It takes the className and the other div props.
data-slot"bar-chart-list-items"The display: contents wrapper around the charts, so a grid or flex layout on the List lays out the cards.

Chart color tokens

Every mantle color name has one chart token, --color-chart-<name>, and a series with color="<name>" paints it. The legend swatch and the tooltip stroke paint the same token.

CSS VariableDescription
--color-chart-<hue>One per hue: amber, blue, cyan, emerald, fuchsia, gray, green, indigo, lime, orange, pink, purple, red, rose, sky, teal, violet, and yellow. Light mode paints the hue's 600 step and dark mode its 500 step, because the 500 step reads washed out on white.
--color-chart-<functional>One per functional name, as an alias of the hue its status color uses: accent and info paint sky, danger paints rose, important paints purple, success paints emerald, and warning paints amber. neutral paints neutral-600 in light mode and neutral-500 in dark mode.
--color-chart-decorativeThe neutral fill every series wears on a decorative chart, in place of its own color.

Color and accessibility lists what each name measures against the card. A series that means good or bad (an error rate, pass and fail) wears a functional name such as danger or success.

The color prop also takes any CSS color string as an escape hatch. A static color (a raw hex) does not adapt across themes, so prefer a per-theme var(--token), and measure it against the card and against the other colors on the chart yourself.

Restyle a color name

Two public paths change what a series paints:

  • One series: pass a different color on BarChart.Bar, a color name or any CSS color string.
  • One chart: redeclare the token on BarChart.Root: className="[--color-chart-blue:var(--color-brand)]". Every series on that chart with color="blue" picks the new value up. So do its legend swatch and tooltip stroke.

The chart paints every token as CSS, so the browser resolves it inside the Root's own cascade, with no computed-style read and no hidden probe element. A declaration scoped to one Root wins for that chart alone, and sibling charts on the page keep the theme value. Declare the same custom property higher up (on a dashboard wrapper, or at :root) to retheme a whole subtree.

Both paths want a var() reference rather than a raw hex, for the reason Brand colors gives. A restyled name leaves mantle's measurements behind, so the measurement is yours. The #d07c00 below measures 3.19:1 on the light card surface.