# Sankey Chart (/docs/charts/components/sankey)

Use a Sankey chart to show how a total flows through stages, like energy from its sources through zones to its uses, where each ribbon's width is its share.

<Example caption="Hover a ribbon to see its value. Press a node in the legend to highlight its routes.">
<Basic />

```tsx
"use client";

import { SankeyChart, type SankeyFlowData, type SankeyNodeConfig } from "@kind-ui/charts";

const data = {
  nodes: [
    { id: "solar", name: "Solar" },
    { id: "wind", name: "Wind" },
    { id: "north", name: "North" },
    { id: "south", name: "South" },
    { id: "homes", name: "Homes" },
    { id: "industry", name: "Industry" },
  ],
  links: [
    { id: "solar-north", source: "solar", target: "north", value: 30 },
    { id: "solar-south", source: "solar", target: "south", value: 20 },
    { id: "wind-north", source: "wind", target: "north", value: 15 },
    { id: "wind-south", source: "wind", target: "south", value: 35 },
    { id: "north-homes", source: "north", target: "homes", value: 25 },
    { id: "north-industry", source: "north", target: "industry", value: 20 },
    { id: "south-homes", source: "south", target: "homes", value: 20 },
    { id: "south-industry", source: "south", target: "industry", value: 35 },
  ],
} satisfies SankeyFlowData;

const config = {
  solar: { label: "Solar", color: "#d29319" },
  wind: { label: "Wind", color: "#0f8b8d" },
  north: { label: "North", color: "#733bff" },
  south: { label: "South", color: "#d27559" },
  homes: { label: "Homes", color: "#447fd1" },
  industry: { label: "Industry", color: "#569951" },
} satisfies SankeyNodeConfig;

export default function EnergyFlowChart() {
  return (
    <SankeyChart
      config={config}
      data={data}
      height={260}
      nodePadding={16}
      sort={false}
      aria-label="Energy from solar and wind through two zones to homes and industry, in MWh"
    >
      <SankeyChart.Nodes />
      <SankeyChart.Links
        render={(link) => <SankeyChart.Link {...link} pathProps={{ strokeOpacity: 0.6 }} />}
      />
      <SankeyChart.Tooltip formatter={(value) => `${value} MWh`} />
      <SankeyChart.Legend />
    </SankeyChart>
  );
}
```
</Example>

## Installation [#installation]

```bash tab="shadcn"
npx shadcn@latest add @kind-ui/sankey-chart
```

```bash tab="npm"
npm install @kind-ui/charts motion recharts
```

## Composition [#composition]

```text
SankeyChart
├── SankeyChart.Nodes
│   ├── SankeyChart.Node
│   └── SankeyChart.NodeLabel
├── SankeyChart.Links
│   └── SankeyChart.Link
├── SankeyChart.Tooltip
├── SankeyChart.Legend
├── SankeyChart.Table
└── SankeyChart.Content
```

`SankeyChart` holds the flow data, the node config and the accessible name, and draws only the parts you add. `SankeyChart.Nodes` and `SankeyChart.Links` draw the bars and ribbons; leave one out and it isn't drawn. Give the chart a `height`, since it fills its container's width. `SankeyChart.Content` places your own HTML next to the legend.

## Usage [#usage]

### Flow Data [#flow-data]

`data` has `nodes`, each with a unique `id` and a `name`, and `links`, each with a unique `id`, a `source` and `target` node ID, and a `value`. The chart checks the data when it renders and throws on:

- a node with no `config` entry, a link to a node that doesn't exist, or a cycle,
- a negative or non-finite value,
- a middle node whose inflow doesn't equal its outflow,
- two links between the same nodes with the same value.

Model losses as links to their own end node, so every middle node balances. A link with a value of `0` isn't drawn, and a node with no drawn links leaves the plot. `empty` shows when no link has a positive value.

### Node Colors [#node-colors]

`config` gives every node ID a `label` and `color`, and the legend lists nodes in its order. A node takes its own color and a ribbon takes its source node's color. Pressing a legend item highlights the node and every route through it, and dims the rest.

Ribbons are opaque, so they hide each other where they cross. Return `SankeyChart.Link` from `SankeyChart.Links`' `render`, as above, with a lower `strokeOpacity` in `pathProps` to let crossings show through.

`nodeWidth`, `nodePadding`, `linkCurvature` and `sort` come from Recharts. Pass `sort={false}` to keep nodes in data order.

### Labels and Gradients [#labels-and-gradients]

Pass a `render` function to `SankeyChart.Nodes` to draw each node yourself. Return `SankeyChart.Node` with `SankeyChart.NodeLabel` beside it, and leave room for the labels with `margin`. `showValues` adds each node's total. Set `material="gradient"` on `SankeyChart.Link` to blend each ribbon from its source to its target color:

<Example caption="Each label shows its node's total. Ribbons blend from source to target.">
<Labels />

```tsx
"use client";

import { SankeyChart, type SankeyFlowData, type SankeyNodeConfig } from "@kind-ui/charts";

const data = {
  nodes: [
    { id: "solar", name: "Solar" },
    { id: "wind", name: "Wind" },
    { id: "homes", name: "Homes" },
    { id: "industry", name: "Industry" },
  ],
  links: [
    { id: "solar-homes", source: "solar", target: "homes", value: 35 },
    { id: "solar-industry", source: "solar", target: "industry", value: 25 },
    { id: "wind-homes", source: "wind", target: "homes", value: 15 },
    { id: "wind-industry", source: "wind", target: "industry", value: 25 },
  ],
} satisfies SankeyFlowData;

const config = {
  solar: { label: "Solar", color: "#d29319" },
  wind: { label: "Wind", color: "#0f8b8d" },
  homes: { label: "Homes", color: "#447fd1" },
  industry: { label: "Industry", color: "#569951" },
} satisfies SankeyNodeConfig;

const sources = new Set(data.links.map((link) => link.source));

export default function LabeledFlowChart() {
  return (
    <SankeyChart
      config={config}
      data={data}
      height={220}
      nodePadding={24}
      sort={false}
      margin={{ top: 8, right: 112, bottom: 8, left: 112 }}
      aria-label="Energy from solar and wind to homes and industry, in MWh"
    >
      <SankeyChart.Nodes
        render={(node) => (
          <g>
            <SankeyChart.Node {...node} />
            <SankeyChart.NodeLabel
              node={node}
              data={data}
              side={sources.has(node.payload.id) ? "left" : "right"}
              showValues
              valueFormatter={(value) => `${value} MWh`}
              fill="currentColor"
            />
          </g>
        )}
      />
      <SankeyChart.Links
        render={(link) => (
          <SankeyChart.Link {...link} material="gradient" pathProps={{ strokeOpacity: 0.6 }} />
        )}
      />
      <SankeyChart.Tooltip formatter={(value) => `${value} MWh`} />
    </SankeyChart>
  );
}
```
</Example>

A node's `icon` in `config` shows beside its label. `position="inside"` clips the label to the node instead; the tooltip still has the full name.

Set `finish="clay"` or `"glow"` on `SankeyChart.Node` or `SankeyChart.Link` for a surface finish; see [Materials](../guides/materials.mdx).

### Accessibility [#accessibility]

Ribbons and nodes aren't reachable from the keyboard on their own. Add `SankeyChart.Table` with a `caption` for a table of every link and its value. Pass it `onInspect` to add a button per row, and `activeLinkId` to mark the selected one, for a keyboard way to pick a flow. You can also give each `SankeyChart.Link` keyboard handlers and ARIA attributes through `pathProps`.

### Motion [#motion]

Pass `animate` to draw the ribbons in when the chart mounts, or `animate={{ revealDurationMs: 900 }}` to change the duration (450ms by default). Sankey charts don't animate by default. When the reader prefers reduced motion, the diagram appears without drawing in. See [Motion](../guides/motion.mdx).

### Loading [#loading]

Set `loading` while the data is on its way. The chart keeps its size and shows a placeholder diagram, which holds still when the reader prefers reduced motion. Screen readers hear `loadingLabel` ("Loading chart" by default):

```tsx
<SankeyChart loading={isPending} loadingLabel="Loading energy flows" {...props}>
```

## API Reference [#api-reference]

### SankeyChart [#sankeychart]

### SankeyChartOptions

| Prop               | Type                                                                                                                                                                                                                            | Description                                                                                                                                                                                                        |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `aria-label?`      | `string \| undefined`                                                                                                                                                                                                           | Defines a string value that labels the current element. The chart's accessible name. Pass this or `aria-labelledby`.                                                                                               |
| `aria-labelledby?` | `string \| undefined`                                                                                                                                                                                                           | Identifies the element (or elements) that labels the current element. The id of an element that names the chart. Pass this or `aria-label`.                                                                        |
| `interaction?`     | `ChartInteractionConfig \| undefined`                                                                                                                                                                                           | What pressing a legend item does: highlight a series (the default) or hide and show it.                                                                                                                            |
| `legendPosition?`  | `"bottom" \| "top"`                                                                                                                                                                                                             | Places the legend and other HTML parts above or below the plot. Default: `"bottom"`                                                                                                                                |
| `frameProps?`      | `` (Omit<ChartProviderProps, "children" \| "config" \| "defaultVisibleSeries" \| "emphasis" \| "interaction" \| "nonce" \| "onVisibleSeriesChange" \| "visibleSeries"> & { [key: `data-${string}`]: unknown; }) \| undefined `` | Attributes, handlers and ref for the outer HTML frame. Plot props remain on the chart.                                                                                                                             |
| `data`             | `SankeyFlowData`                                                                                                                                                                                                                | Nodes and links. Every node ID needs a `config` entry, and each middle node's inflow must equal its outflow.                                                                                                       |
| `animate?`         | `boolean \| SankeyAnimation \| undefined`                                                                                                                                                                                       | Draws the ribbons in on mount. Pass `{ revealDurationMs }` to change the duration (450ms by default). Custom link renderers draw in only if they use `SankeyChart.Link`. Reduced motion skips it. Default: `false` |
| `loading?`         | `boolean \| undefined`                                                                                                                                                                                                          | Shows a placeholder diagram and hides the legend and tooltip while the data is on its way.                                                                                                                         |
| `loadingLabel?`    | `string \| undefined`                                                                                                                                                                                                           | What screen readers hear while `loading` is on. Default: `"Loading chart"`                                                                                                                                         |
| `empty?`           | `ReactNode`                                                                                                                                                                                                                     | What shows when no link has a positive value. Default: `"No positive flows"`                                                                                                                                       |
| `config`           | `Readonly<Record<string, { label: string; color: string; icon?: ReactNode; }>>`                                                                                                                                                 | A label and color, plus an optional icon, for every node ID. The legend lists nodes in this order.                                                                                                                 |
| `responsive?`      | `boolean \| undefined`                                                                                                                                                                                                          | Sizes the diagram to its container. Set `false` to use a numeric `width` and `height`. Default: `true`                                                                                                             |

### SankeyChart.Link [#sankeychartlink]

### SankeyLinkOptions

| Prop           | Type                                    | Description                                                                                                                         |
| -------------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `color?`       | `string \| undefined`                   | The source color. Defaults to the source node's `config` color.                                                                     |
| `material?`    | `"gradient" \| "solid"`                 | `"solid"` paints the ribbon in the source node's color; `"gradient"` blends from the source to the target color. Default: `"solid"` |
| `finish?`      | `"clay" \| "glow" \| "plain"`           | A surface finish for the ribbon. Default: `"plain"`                                                                                 |
| `targetColor?` | `string \| undefined`                   | The target color for `"gradient"`. Defaults to the target node's `config` color.                                                    |
| `pathProps?`   | `SVGProps<SVGPathElement> \| undefined` | Props for the ribbon's `path`, like handlers and ARIA attributes. The computed path and width always win.                           |

### SankeyChart.Node [#sankeychartnode]

### SankeyNodeOptions

| Prop         | Type                                    | Description                                                     |
| ------------ | --------------------------------------- | --------------------------------------------------------------- |
| `color?`     | `string \| undefined`                   | The node color. Defaults to the node's `config` color.          |
| `rectProps?` | `SVGProps<SVGRectElement> \| undefined` | Props for the node's `rect`, like handlers and ARIA attributes. |
| `finish?`    | `"clay" \| "glow" \| "plain"`           | A surface finish for the node. Default: `"plain"`               |

### SankeyChart.NodeLabel [#sankeychartnodelabel]

### SankeyNodeLabelOptions

| Prop              | Type                                                                                               | Description                                                                                                                  |
| ----------------- | -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `offset?`         | `number \| undefined`                                                                              | Gap between the node and an outside label. Default: `8`                                                                      |
| `node`            | `Pick<SankeyNodeProps, "height" \| "payload" \| "width" \| "x" \| "y">`                            | The node props from `SankeyChart.Nodes`' `render` callback.                                                                  |
| `data`            | `SankeyFlowData`                                                                                   | The chart's `data`, used for the node's name and value.                                                                      |
| `nodeConfig?`     | `Readonly<Record<string, { label: string; color: string; icon?: React.ReactNode; }>> \| undefined` | The chart's `config`. Shows the node's `icon`, if it has one.                                                                |
| `iconSize?`       | `number \| undefined`                                                                              | Icon size in chart units. Default: `16`                                                                                      |
| `iconGap?`        | `number \| undefined`                                                                              | Gap between the icon and the text. Default: `4`                                                                              |
| `position?`       | `"inside" \| "outside"`                                                                            | `"outside"` sets the label beside the node; `"inside"` clips it to the node. Default: `"outside"`                            |
| `side?`           | `"left" \| "right"`                                                                                | Which side an outside label goes on. Defaults to left for end nodes and right for the rest. Leave chart margin for the text. |
| `showValues?`     | `boolean \| undefined`                                                                             | Adds the node's total after its name. Default: `false`                                                                       |
| `valueFormatter?` | `((value: number) => string) \| undefined`                                                         | Formats the total from `showValues`. Default: `String`                                                                       |

<Caption>
`SankeyChart` also takes every prop of Recharts' [Sankey](https://recharts.github.io/en-US/api/Sankey/), like `margin`, `nodeWidth` and `nodePadding`, and its `onClick`, `onMouseEnter` and `onMouseLeave` receive the node or link with its `id`. `SankeyChart.Tooltip` takes every prop of Recharts' [Tooltip](https://recharts.github.io/en-US/api/Tooltip/), like `formatter`.
</Caption>