# Stacked Chart

Stacked chart for the parts of a total: stacked and 100 % columns, stacked areas, diverging Likert bars, Marimekko and gapped rows.

- Category: Charts
- Page: https://wunderui.com/components/stacked-chart
- Tier: Core and Pro

## Install

Stacked Chart ships with WunderUI Core and Pro in the @wunderui/react package.

## Import

```tsx
import { StackedChart, StackedChartProps, StackedChartReferenceLine, StackedChartVariant } from "@wunderui/react"
```

## Minimal usage

Then use it:

```tsx
import { StackedChart } from "@wunderui/react/charts"

const data = [
  { month: "Jan", direct: 14000, organic: 10000 },
  { month: "Feb", direct: 18000, organic: 11000 },
  { month: "Mar", direct: 16000, organic: 10000 },
  { month: "Apr", direct: 20000, organic: 14000 },
]

export function SessionsByChannel() {
  return (
    <StackedChart
      data={data}
      index="month"
      series={[
        { key: "direct", label: "Direct" },
        { key: "organic", label: "Organic" },
      ]}
      label="Sessions by channel"
    />
  )
}
```

Expected result: You see four columns, each made of a Direct and an Organic part stacked on one zero line.

## When to use

### Use Stacked Chart for

- The parts that make up a total, per category or period
- Shares of a whole over time (the 100 % variants)
- Survey answers on a scale (the diverging stack)
- Two dimensions at once: the width of a column says how big a group is (Marimekko)

### Use something else

- [Bar Chart](https://wunderui.com/components/bar-chart) for comparing single values or a few series side by side
- [Pie Chart](https://wunderui.com/components/pie-chart) for the parts of one total, at one moment
- [Area Chart](https://wunderui.com/components/area-chart) for overlapping series that are not parts of one total
- [Treemap](https://wunderui.com/components/treemap) for parts of a hierarchy

## Keyboard

The plot is focusable, so the chart works without a pointer.

| Key | Action |
|---|---|
| `Tab` or `Shift+Tab` | Moves focus to the plot and away from it. The plot is one tab stop; so is every legend badge. |
| `ArrowRight` or `ArrowLeft` | Moves to the next or previous category. The tooltip follows, and a live region announces the one you are on. The first press starts at the first one (Left: the last one). |
| `Home` or `End` | Jumps to the first or last category. |
| `Shift+ArrowRight` or `Shift+ArrowLeft` | Extends a selected range from the point you started on. A range is only selected when `onSelectedRangeChange` is set. |
| `Escape` | Clears the active point and the selected range. |
| `Enter` or `Space` | On a legend badge of a ChartCard: switches its series off or on. The last visible series stays on. |

On horizontal and diverging stacks the categories run top to bottom, so Up and Down walk them instead of Left and Right.

## Behavior

What the chart does on its own and what the page decides.

- **Stacking order:** Series stack in the order you list them, from the bottom or left. Put the part that matters most there, where the eye compares it best.
- **Normalized variants:** The 100 percent bar and area variants and the Marimekko scale every stack to 100. The axis reads percent while the tooltip and table still show the raw amounts.
- **Diverging stack:** The diverging bar puts 0 in the middle. You say how many series, counted from the first, go to the left (default: half of them).
- **Segments:** Gap and bar width shape the segments, and the Marimekko percentages can be toggled. A series switched off in the legend keeps its place and fades, so the rest of the stack doesn't jump.
- **Negative values:** On the plain stacked bars and the stacked area, negative values stack from zero the other way, so the gains and losses of one category read in one column (profit and loss per unit). A solid line marks zero between the dashed grid lines, and the tooltip keeps the sign of every row.
- **Reference line:** A reference line is drawn over the marks without hover: across columns with its label at the end, down the horizontal stacks with its label at the top. The axis grows to reach it, and the label names it for everyone, so it never relies on colour alone.
- **Loading, empty and error:** The chart keeps its size while loading, empty or failed, so the card never jumps. Add a retry handler to show a Try again button on error.
- **Legend:** A ChartCard shows the series as badges. With two or more series each badge switches its series off, but the last visible one stays on.
- **Data table:** The chart renders its data as a table for screen readers, in the same order as the plot. A ChartCard can show that table on screen through a toggle that keeps the card's height.
- **Size:** The chart fills the width of its container, and you set the plot height. Text never scales, so labels keep their size at every width.

## Motion

The enter sequence and the hover follow the library's motion tokens.

- **Grow:** Each stack grows out of the zero line as one piece, left to right, when the chart first comes into view, after loading and when the data changes. The area variants wipe in with their edges.
- **Hover:** The hovered category keeps its strength and the others dim. The segment under the pointer stays bright while the rest of its stack dims too, and its row stays bright in the tooltip; the area variants do the same per layer.
- **Reduced motion:** With reduced motion the chart appears at once. The tooltip, the crosshair and every state still work.

## Anatomy

- `StackedChart`: Takes the data, an index field and the series in stacking order, from the bottom or left. Options split a diverging stack, shape the segments and toggle the Marimekko percentages.
- `Plot`: The focusable region. Arrow keys walk the categories (Up and Down for horizontal stacks), and Shift with an arrow or a drag selects a range.
- `Grid and axes`: A value axis from 0, or 0 to 100 percent on the normalized variants and the Marimekko. Diverging stacks put 0 in the middle and the negative side on the left.
- `Segments`: One segment per series and category, stacked in order. A series switched off in the legend keeps its place and fades, so the rest of the stack doesn't jump.
- `Hover points`: On the two area variants, a ringed point on top of each stack follows the hovered category. The bar variants use the hover band instead.
- `Tooltip`: The category and one row per visible part with its raw value, plus a change chip for the first series. Normalized variants still show amounts here while the axis reads percent.
- `Loading, empty and error`: A bar-shaped skeleton while loading. The empty and error messages replace the stack.
- `Data table and live region`: A hidden table with the raw values, not percentages, so screen readers hear the same numbers the tooltip shows.
- `Chart Reference Line`
- `Chart Stacks`
- `Chart Segment Labels`
- `Chart Layers`
- `Chart Zero Line`

## Best practices

### When to use

- Use it when the composition of each total matters as much as the total. Use BarChart when only totals are compared, and its grouped variant when each part is compared across categories.

### Do

- Order the series by importance, with the part people compare most at the baseline. Only the bottom (or left) segment shares a common start, so only it can be compared exactly.
- Switch to a 100 percent variant when the shares matter and the totals do not. All bars then reach 100 and segment sizes are comparable between categories.
- Use the diverging variant for survey scales such as strongly disagree to strongly agree. With an odd number of series the middle one is neutral and straddles zero.

### Don't

- Don't stack more than five series. Thin segments lose their labels and hover target, and the hues get hard to match to the legend.
- Don't stack values that aren't additive, such as averages or rates. A stack implies the parts sum to the total.

## API reference

### StackedChart

| Prop | Type | Default | Description |
|---|---|---|---|
| data* | readonly ChartDatum[] |  | One object per category / point. |
| index* | string |  | Field holding the category label (x axis; y axis for horizontal bars). |
| series* | readonly ChartSeries[] |  | The series to draw, in order. |
| activeIndex | number \| null |  | The active point (hovered or focused) as an index into `data`, to control it yourself. `null` shows none. |
| animate | boolean |  | Enter sequence (draw, wipe, grow) on scroll into view, after loading and on new data. Default true; off with reduced motion. |
| animationKey | string \| number |  | Change it to play the enter sequence again (e.g. `useChartReload().version`). New `data` replays it by itself. |
| aspectRatio | number |  | Width ÷ height when `height` is not set. Default 2.6. |
| axisFormatter | ChartValueFormatter |  | Value-axis labels; defaults to `valueFormatter`. |
| barWidth | number |  | Maximum bar width (thickness for horizontal stacks) in px. |
| categoryAxis | boolean |  | Category-axis labels (default true). |
| categoryFormatter | (label: string) => string |  | Shortens category labels on the axis, e.g. "Mar 12" → "Mar"; tooltip and pill keep the full label. |
| categoryTicks | readonly string[] |  | Only these category labels are shown on the axis (the rest stay hoverable). |
| className | string |  | Extra classes for the root element of the chart. |
| defaultActiveIndex | number \| null |  | The point that is active at first, for an uncontrolled chart. It shows the tooltip without a pointer. |
| defaultSelectedRange | ChartRange \| null |  | The range that is selected at first, for an uncontrolled chart. |
| description | string |  | Screen-reader summary; generated from the data when omitted. |
| emptyDescription | string |  | Text under the title in the empty state. |
| emptyTitle | string |  | Title of the message in the empty state. |
| errorDescription | string |  | Text under the title in the error state. |
| errorTitle | string |  | Title of the message in the error state. |
| grid | boolean |  | Grid lines (default true). |
| gridFade | boolean |  | The grid fades out towards both ends (default true). |
| gridIntervals | number |  | Number of equal grid intervals. Default: one per 44 px of plot height, capped by the size class (xs 2, sm 3, md 3, lg 4, xl 5). |
| gridStyle | "solid" \| "dashed" |  | Grid lines are dashed 4 / 4 by default; `solid` draws them through. |
| height | number |  | Fixed height of the plot frame in px. Without it the height follows the width (`aspectRatio`, `minHeight`, `maxHeight`): 220 px on a phone, up to 434 px (the plot of the Figma large card) from about 1130 px wide. |
| hiddenSeries | readonly string[] |  | Series keys that are switched off (legend toggle): drawn faded, dimmed in the tooltip. |
| includeZero | boolean |  | The value axis starts at 0 (owner rule, default). `false` fits the data (prices, temperatures). |
| label | string |  | Accessible name, e.g. the card title. |
| maxHeight | number |  | Highest height from `aspectRatio`. Default 434. |
| minHeight | number |  | Lowest height from `aspectRatio`. Default 220. |
| negativeCount | number |  | `diverging-stacked-bar`: how many of the first series go to the left of zero (default: half, rounded down; with an odd count the middle series is neutral and straddles zero — a Likert scale). |
| onActiveIndexChange | (index: number \| null) => void |  | Called with the index when the pointer or the arrow keys move to another point, and with `null` when they leave. Use it to show the hovered value in a headline. |
| onRetry | () => void |  | Shows a Try again button in the error state and calls this when it is pressed. |
| onSelectedRangeChange | (range: ChartRange \| null) => void |  | Called when a drag across the plot or Shift with an arrow key changes the range, and with `null` when Escape or a click clears it. |
| pattern | ChartPattern \| ChartPattern[] |  | One pattern form from the shared pattern library (`diagonal-lines`, `polka-dots`, `crosshatch` …) for every series (segments and stacked areas), drawn in its colour on a tint of it, for print and colour-blind reading. A list keeps its first entry; a mark under 20 px on its shorter side stays solid. |
| rangeSelectable | boolean |  | Allow selecting a range by dragging or Shift + arrow keys. On when `onSelectedRangeChange` is set. |
| referenceLine | StackedChartReferenceLine \| StackedChartReferenceLine[] |  | A limit or a target as a line across the plot: `{ value, label?, tone?, dashed? }`. Horizontal over columns and areas, vertical over the horizontal stacks; the value axis always reaches it. Tone `neutral` (default), `destructive`, `warning`, `success` or `primary`; dashed by default. |
| resolution | "auto" \| "full" |  | `auto` (default): lines and areas draw at most 1.5 points per pixel (LTTB; hover and tooltip keep every point), and bars on a time axis that would get thinner than they may are gathered into weeks, months … `full` draws every point and eve… |
| segmentGap | number |  | Gap between stacked segments in px (default 0; gapped rows 4). |
| selectedRange | ChartRange \| null |  | The selected range as inclusive indices `[from, to]` into `data`, to control it yourself. `null` selects nothing. |
| showSegmentLabels | boolean | true | Segment labels inside the marimekko cells ("39 %"). Default true. |
| state | "ready" \| "loading" \| "empty" \| "error" |  | `loading` shows the chart-shaped skeleton, `empty` and `error` a message in the plot. |
| tooltip | boolean |  | Tooltip on hover / keyboard focus. Default true. |
| tooltipTitle | (datum: ChartDatum, index: number) => React.ReactNode |  | Title line of the tooltip; defaults to the category label. |
| valueAxis | boolean |  | Value-axis labels (default true). Off for compact cards and sparkline-like plots. |
| valueAxisPlacement | "auto" \| "outside" \| "inside" |  | Where the value labels go: `outside` left of the plot, `inside` in the plot above their grid lines (saves the label column on narrow charts). `auto` (default) puts them left of the plot at every size; `inside` is opt-in. |
| valueAxisSide | "left" \| "right" |  | Side of the value axis (vertical charts). `right` is the price axis of trading charts. |
| valueDomain | readonly [number, number] |  | Fix the value domain instead of fitting it to the data (still rounded to nice steps). |
| valueFormatter | ChartValueFormatter |  | Values in tooltip, labels, table and live region. Default: 42000 → "42k". |
| valueTicks | readonly number[] |  | Exact value-axis ticks (ascending), e.g. [0, 10000, … 70000]; replaces the nice-step domain. |
| variant | "stacked-bar" \| "stacked-bar-100" \| "horizontal-stacked-bar" \| "stacked-area" \| "stacked-area-100" \| "stacked-gradient-bar" \| "diverging-stacked-bar" \| "marimekko" \| "gapped-horizontal-stacked-bar" | "stacked-bar" | Figma variant. Default `stacked-bar`. |
| width | number |  | Fixed width instead of filling and measuring the container. |
| xScale | "band" \| "time" |  | `band` (default): the categories sit side by side in equal bands. `time`: the `index` field holds dates (Date, ms or a string such as "2026-03-01"); points sit at their real distance, the axis picks its tick level (hours → days → weeks → m… |

## Examples

### States

### Table view

### Patterns

### Negative values

### Reference line

## In context

### Requests by Status Code

Edge network requests stacked by status code, per two hours. The legend switches classes off.

### Plan Mix 100 %

Share of MRR by plan per month.

### Tickets by Channel

Support tickets per week stacked by channel, next to the agent list.

## For AI agents

`get_component("stacked-chart")`

Hand your agent this page as Markdown or the WunderUI MCP server, not a screenshot.
