Charts
StackedBarChart
A total per category and what it is made of. StackedBarChart takes your rows, the field for the category and one entry per series, and handles the scales, the tooltip, the keyboard and the screen reader. It takes the same rows and the same series as GroupedBarChart, so switching between the two is a change of component name.
When to use it #
Use it when the total matters and so does its composition: monthly cost split into labor, materials and subcontract, jobs per quarter split by crew. One row is one stack, and each series is one segment of it. Keep it to about five series, because the tones repeat from the sixth. To compare series with each other inside a category, use GroupedBarChart. For one series, use BarChart. For trends over many periods, LineChart usually reads better.
Import #
npm i tally-chartsimport { StackedBarChart } from 'tally-charts'
import 'tally-charts/theme.css'Examples #
Each series says which field it reads and how to name it. The first series sits on the baseline, and the others stack on it in the order of the series array. The label above each stack is its total. Props stay serializable here, so the chart renders in a server component. The third series sets tone: 'neutral' in its series object.
| Month | Labor | Materials | Subcontract | Total |
|---|---|---|---|---|
| Jan | $24K | $18K | $9K | $51K |
| Feb | $26K | $20K | $10K | $56K |
| Mar | $27K | $20K | $11K | $58K |
| Apr | $28K | $21K | $17K | $66K |
| May | $27K | $19K | $10K | $56K |
| Jun | $29K | $20K | $20K | $69K |
import { StackedBarChart } from 'tally-charts'
import type { ExampleMeta } from '../types'
export const meta = {
id: 'stacked-bar-chart/cost-by-type',
title: 'Monthly job cost by type',
rscSafe: true,
} satisfies ExampleMeta
const months = [
{ month: 'Jan', labor: 24000, materials: 18000, subcontract: 9000 },
{ month: 'Feb', labor: 26000, materials: 20000, subcontract: 10000 },
{ month: 'Mar', labor: 27000, materials: 20000, subcontract: 11000 },
{ month: 'Apr', labor: 28000, materials: 21000, subcontract: 17000 },
{ month: 'May', labor: 27000, materials: 19000, subcontract: 10000 },
{ month: 'Jun', labor: 29000, materials: 20000, subcontract: 20000 },
]
// Props stay serializable (no functions): the page is a server component.
export default function CostByType() {
return (
<StackedBarChart
data={months}
x="month"
series={[
{ id: 'labor', label: 'Labor', value: 'labor' },
{ id: 'materials', label: 'Materials', value: 'materials' },
{ id: 'subcontract', label: 'Subcontract', value: 'subcontract', tone: 'neutral' },
]}
format="currency-compact"
domain={[0, 80000]}
height={260}
title={meta.title}
description="Labor is the largest part of the cost every month. Total cost peaked at $69K in June."
/>
)
}
Target and over budget #
target draws a line at a value, with an optional label. Stacks routinely pass the target, so the label is drawn outside the plot: above it when horizontal, and in the right margin when vertical. That margin grows with the label, so keep the label short: a long label takes plot width, most noticeably on narrow screens. Add over: 'loss' and the part of each stack beyond the target is painted in that tone, whichever series it belongs to. A segment that crosses the target is split in two at the line. The total label of a stack over the target takes the same tone, so the state is also text. A total label never sits on the line: when the line would cross it, the label moves just beyond the line. over only colours the positive stack, and it needs a target above zero. The tooltip swatch shows the series' tone even when the pointer is on the part painted in the over tone.
import { StackedBarChart } from 'tally-charts'
import type { ExampleMeta } from '../types'
export const meta = {
id: 'stacked-bar-chart/over-budget',
title: 'Monthly job cost against the $60K budget',
rscSafe: true,
} satisfies ExampleMeta
const months = [
{ month: 'Jan', labor: 24000, materials: 18000, subcontract: 9000 },
{ month: 'Feb', labor: 26000, materials: 20000, subcontract: 10000 },
{ month: 'Mar', labor: 27000, materials: 20000, subcontract: 11000 },
{ month: 'Apr', labor: 28000, materials: 21000, subcontract: 17000 },
{ month: 'May', labor: 27000, materials: 19000, subcontract: 10000 },
{ month: 'Jun', labor: 29000, materials: 20000, subcontract: 20000 },
]
export default function OverBudget() {
return (
<StackedBarChart
data={months}
x="month"
series={[
{ id: 'labor', label: 'Labor', value: 'labor' },
{ id: 'materials', label: 'Materials', value: 'materials' },
{ id: 'subcontract', label: 'Subcontract', value: 'subcontract', tone: 'neutral' },
]}
target={{ value: 60000, label: 'budget $60K', over: 'loss' }}
format="currency-compact"
domain={[0, 80000]}
height={260}
title={meta.title}
description="April and June ran over budget, at $66K and $69K, both because of subcontract work."
/>
)
}
orientation="horizontal" puts the categories on the left and the totals at the end of each bar. x is still the category and the series values are still the values. The height follows the number of rows unless you set height or aspectRatio. grid and valueAxis are independent: valueAxis="none" hides the value axis and keeps the grid lines at the default ticks, and grid={false} removes the lines.
import { StackedBarChart } from 'tally-charts'
import type { ExampleMeta } from '../types'
export const meta = {
id: 'stacked-bar-chart/horizontal',
title: 'Hours booked by crew, this week',
rscSafe: true,
} satisfies ExampleMeta
const crews = [
{ crew: 'North', install: 96, repair: 42, travel: 18 },
{ crew: 'South', install: 74, repair: 55, travel: 22 },
{ crew: 'West', install: 58, repair: 31, travel: 14 },
{ crew: 'East', install: 41, repair: 38, travel: 9 },
]
export default function Horizontal() {
return (
<StackedBarChart
data={crews}
x="crew"
orientation="horizontal"
series={[
{ id: 'install', label: 'Install', value: 'install' },
{ id: 'repair', label: 'Repair', value: 'repair' },
{ id: 'travel', label: 'Travel', value: 'travel', tone: 'neutral' },
]}
title={meta.title}
description="North booked the most hours, 156, mostly on installs. Travel is the smallest part for every crew."
/>
)
}
Legend #
The chart has no legend of its own. Compose Legend with the same tones, as with LineChart. For a series without a tone, use the tone from the default order.
import { Legend, StackedBarChart } from 'tally-charts'
import type { ExampleMeta } from '../types'
export const meta = {
id: 'stacked-bar-chart/with-legend',
title: 'Tickets opened by priority, per week',
rscSafe: true,
} satisfies ExampleMeta
const weeks = [
{ week: 'W1', low: 34, medium: 21, high: 6 },
{ week: 'W2', low: 29, medium: 25, high: 9 },
{ week: 'W3', low: 38, medium: 19, high: 4 },
{ week: 'W4', low: 31, medium: 28, high: 11 },
]
// The chart has no legend of its own: compose `Legend` with the same tones.
export default function WithLegend() {
return (
<div>
<Legend
items={[
{ label: 'Low', tone: 'accent' },
{ label: 'Medium', tone: 'accent-soft' },
{ label: 'High', tone: 'warn' },
]}
/>
<StackedBarChart
data={weeks}
x="week"
series={[
{ id: 'low', label: 'Low', value: 'low' },
{ id: 'medium', label: 'Medium', value: 'medium' },
{ id: 'high', label: 'High', value: 'high' },
]}
domain={[0, 80]}
height={260}
title={meta.title}
description="Low priority tickets are the largest part every week. High priority peaked at 11 in week 4."
/>
</div>
)
}
Series, tones and fills #
A BarSeries has an id that is unique within the chart, a label for the tooltip, the announcements and the data table header, a value accessor, and optionally a tone and a fill. Without a tone, series take the tones by position: accent, accent-soft, warn, neutral, gain, and then the order repeats. The default order never uses loss; choose it explicitly. Tone is the series, and fill is the state: a row's fill applies to every segment of that row, and when both are set, the row's fill wins. The part painted by target.over is always solid.
Negative values and totals #
Positive values stack up from zero, and negative values stack down from zero on their own, so a diverging stack has a positive and a negative part. The label shows the net sum of the row, above the positive stack. A missing or non-numeric value draws nothing, counts as zero in the total, and the stack closes up with no hole. The gap between segments is gap px, taken from the far end of every segment except the outermost one, so the stack keeps its length, except that a non-zero piece shorter than 1 px is drawn 1 px long; the total label always sits at the true value. A segment not longer than the gap plus 1 px keeps 1 px, and a segment thinner than that is covered by its neighbour. With valueLabel="total" (the default) every stack is labelled; in a vertical chart, when any label is wider than its column, none is drawn at that width, and the totals stay in the tooltip and the data table. Use valueLabel="none" to turn the labels off. A category whose values are all zero or missing has no total label and is skipped by the keyboard; the data table still lists it.
Props #
| Name | Type | Default | Required | Description |
|---|---|---|---|---|
activeId | Id | null | — | No | — |
animate | boolean | — | No | — |
aria-labelledby | string | — | No | Id of an element that names the chart; it wins over |
aspectRatio | number | — | No | width / height. Used when |
axis | TickSpec | 'none' | every category | No | Category axis ticks, or 'none'. Default: every category. |
axisFormat | AxisFormat | the category itself | No | Category axis labels: a function of the category. Number presets and date formats don't apply to categories and are ignored with a development warning. Default: the category itself. |
chartId | string | — | No | Prefix for pattern and mask ids. React's |
children | ReactNode | — | No | — |
className | string | — | No | — |
data | readonly D[] | — | Yes | — |
dataTable | boolean | DataTableOptions | true | No | Hidden data table for screen readers: |
description | string | — | No | Accessible description, usually the takeaway sentence. |
dimInactive | boolean | — | No | — |
domain | readonly [number, number] | every stack total and the target, including zero, nice ticks | No | Value domain. Default: every stack total and the target, including zero, nice ticks. |
empty | ReactNode | "No data" | No | Rendered instead of the plot when |
fill | PerItem<D, Fill | undefined> | — | No | Fill for every segment of a row; |
format | FormatSpec | 'number' | No | Format for tooltips, announcements and the data table. Default 'number'. |
gap | number | 2 | No | Gap between the segments of a stack in px. Default 2. |
grid | boolean | true | No | Grid lines at the value ticks. Default true. |
height | number | 240 unless `aspectRatio` is set | No | Height in px. Default 240 unless |
id | Accessor<D, Id> | the data index | No | Row id. A segment's id is |
initialWidth | number | 640 | No | Width used for server rendering and the first client render. Default 640. |
keyboardHint | string | "Use arrow keys to move between points, Home and End for first and last, Escape to clear.", plus " Press Enter to select." while the active point (or the first, before one is active) can be selected with `onSelect` | No | Instructions read with the chart when it takes keyboard focus. Default: "Use arrow keys to move between points, Home and End for first and last, Escape to clear.", plus " Press Enter to select." while the active point (or the first, before one is active) can be selected with |
label | Accessor<D, string> | `x` | No | Category label for tooltips, announcements and the data table. Defaults to |
margin | Partial<Margin> | — | No | — |
onActiveChange | (id: Id | null, point: ChartPoint<D> | null) => void | — | No | Called with the new active id, and its point; |
onSelect | (id: Id, point: ChartPoint<D>) => void | — | No | Called on click, Enter or Space; |
orientation | 'vertical' | 'horizontal' | 'vertical' | No | Default 'vertical'. |
padding | number | 0.3 | No | Padding between stacks, 0–1 of the step. Default 0.3. |
series | readonly BarSeries<D>[] | — | Yes | One segment per series in every stack; the first series sits on the baseline. |
style | CSSProperties | — | No | — |
target | number | { value: number; label?: string; over?: Tone } | — | No | A target value, optionally with a label. |
title | string | — | No | Accessible name of the chart; also the default caption of the data table. |
tooltip | ChartTooltip<D> | true | No | Tooltip on hover and focus: |
valueAxis | TickSpec | 'none' | nice ticks | No | Value axis ticks, or 'none'. Default: nice ticks. |
valueAxisFormat | AxisFormat | `format` | No | Value axis labels. Default: |
valueFormat | FormatSpec | `format` | No | Format for value labels. Defaults to |
valueLabel | 'total' | 'none' | 'total' | No | 'total' labels each stack with its total. Default 'total'. |
width | number | — | No | Fixed width in px; turns off container measuring. |
x | Accessor<D, string | number> | — | Yes | Category field: the band axis in both orientations. One row is one stack. |
Series and points #
A segment's id is ${rowId}:${series.id}, where the row id is the id accessor or the data index. Every segment is a point. In onSelect and onActiveChange, the ChartPoint has seriesId with the id of the series, series with its label, and datum with your row. You do not need to parse the id. The default tooltip shows the category, the series of the hovered or focused segment with its tone swatch and value, and the total of the stack.
Keyboard and screen readers #
The chart is a single tab stop. Arrow keys walk the segments stack by stack, and inside a stack in the order of the series array. In a diverging stack, positive and negative segments alternate as the series do. Home and End jump to the first and last segment, Enter or Space selects the active segment when the chart has onSelect, and Esc clears the active segment.
Screen readers get the title and description, then an announcement for each segment the keyboard moves to, such as “Materials, 4 of 6, Apr, $21K”: the series, the position within the series, then the category and the formatted value. A visually hidden data table follows the chart, with one row per category, one column per series and a last column with the total.
Pointer targets of thin segments are small: the hit areas of neighbouring segments meet in the middle of the gap, and the outermost segment's area reaches the edge of the chart, but a thin inner segment is still a small target. The keyboard and the data table reach every value, and they are the equivalents. In forced colors mode (Windows high contrast), tones collapse to a few system colors and several share one, so segments are told apart by their order in the stack and the gap between them, and the over-budget part falls back to the system color of its tone.
The full model is in the accessibility guide.