Sankey Diagram
What is a Sankey diagram?
A Sankey diagram (also called a Sankey chart, Sankey plot or Sankey graph) is a flow diagram that shows how a quantity moves from its sources, through stages, to where it ends up. Each source, stage or end point is a bar called a node. Each flow is a band called a link, drawn as wide as the amount it carries.

A Sankey diagram of one year's energy use in an imaginary country, in terawatt-hours (sample data). Try the interactive version.
- A Sankey diagram shows where a total comes from and where it goes, as bands flowing between bars.
- A band's width is its value, so the biggest flows are the first thing you see.
- At every middle node, what flows in equals what flows out. Anything lost on the way gets its own band and node.
- Use one when something moves through stages: energy, money, materials, people. When nothing flows, a bar or pie chart is clearer.
- Keep it readable: few nodes, few crossings, and small flows grouped together.
How to read a Sankey diagram
- Check what is flowing. Find the unit (kilowatt-hours, dollars, tonnes, people) and the period. Every band on the diagram uses the same unit.
- Read from left to right. The left column holds the sources. Each column to the right is a later stage, and the right-hand column holds the end points. Some end points, such as losses, can sit in a middle column.
- Compare the widths of the bands. A band twice as wide carries twice as much. The height of each node is its total. Use the labels or a tooltip for exact numbers: widths are good for ranking flows, not for reading precise values.
- Follow a band from end to end. Pick a source and trace where its bands go. On an interactive Sankey diagram, hovering over a node or band highlights the whole path.
- Check the balance at each middle node. What flows in should equal what flows out. In the diagram above, node D takes in 15 from A and 15 from B, and sends 5 to E and 25 to F: 30 in, 30 out.
- Look at the end points. They answer the question the diagram was drawn for: how much became useful, how much was spent on each item, how many people finished.
A worked example: where a country's energy goes
The diagram at the top of this page follows 100 terawatt-hours (TWh) of energy through an imaginary country for one year. The numbers are made up but realistic in shape. Because the total is 100, each value is also a percentage.
| Node | Flows in (TWh) | Flows out (TWh) |
|---|---|---|
| Wind and solar, natural gas, biomass, oil | (sources) | 14 + 48 + 8 + 30 = 100 |
| Electricity | 14 + 22 + 3 + 2 = 41 | 13 to losses, 12 to homes, 13 to industry, 3 to transport = 41 |
| Fuels used directly | 26 + 5 + 28 = 59 | 18 to homes, 14 to industry, 27 to transport = 59 |
| Homes | 12 + 18 = 30 | 21 useful + 9 wasted = 30 |
| Industry | 13 + 14 = 27 | 19 useful + 8 wasted = 27 |
| Transport | 3 + 27 = 30 | 9 useful + 21 wasted = 30 |
| End points | Power station losses 13, useful energy 49, wasted heat 38 | (end) = 100 |
Three things stand out once the flows are drawn:
- About half the energy does useful work. 49 of the 100 TWh ends as useful energy; the other 51 TWh is lost as heat.
- Transport is the least efficient sector. Only 9 of its 30 TWh does useful work, against 21 of 30 in homes.
- Making electricity loses energy. 13 of the 41 TWh that goes into making electricity is lost before it reaches anyone.
The table and the diagram hold the same numbers. The table is better for checking a single value; the diagram shows the structure and the big flows in one look.
How to describe a Sankey diagram
Use this template when you report a Sankey diagram:
Of the [total and unit] that entered [the system] in [period], [amount or share] went to [main destination], and [amount or share] ended as [loss or other end point]. The largest single flow was [source] to [target], at [value].
Worked example: "Of the 100 TWh of energy this country used in the year, 49 TWh did useful work and 51 TWh was lost as heat. The largest single flow was oil into fuels used directly, at 28 TWh, and transport turned only 30% of its energy into useful work."
How does a Sankey diagram work?
A Sankey diagram is drawn in four steps. Most tools that make Sankey charts do them for you; knowing them helps you fix a diagram that looks wrong.
- Give each node a column. Sources go in the first column. Every other node goes one column to the right of the furthest-right node that feeds it.
- Choose one scale for the whole diagram. A flow of 10 units must be equally wide everywhere. The busiest column sets the scale, so it fills the height with gaps between its nodes.
- Stack the links on each node. The bands leaving a node are stacked down its edge in the order of the nodes they go to, top to bottom. That keeps crossings to a minimum.
- Draw each link as an S-shaped band from its place on the source node to its place on the target node. It leaves and arrives horizontally, and its vertical thickness is the same all the way across.
To put a band on screen, it is cut into thin slices, and each slice is split into two triangles, which is what graphics hardware draws fastest. The more slices, the smoother the curve. The live example on this page draws every band, and every node, this way.
When to use a Sankey diagram
Use a Sankey diagram when a quantity moves through stages and you want to show how it splits, merges and where it ends up. Typical uses:
- energy and materials: fuels to electricity, end uses and losses; raw material to product, scrap and recycling;
- money: income to spending categories, or a company's revenue to costs and profit;
- people: visitors through a sign-up process, or applicants through a hiring process, including where they drop out;
- any process with losses, where showing what leaves at each stage matters as much as what arrives.
| Chart | Best for |
|---|---|
| Sankey diagram | How a total flows through stages, splits and merges, with losses shown |
| Bar chart (stacked) | Comparing totals and their parts across categories, when nothing flows between them |
| Pie chart | How one total splits into a few parts, at a single stage |
| Treemap | Parts of a total nested in groups (a hierarchy), with no flow from one stage to the next |
The Sankey diagram has two close relatives. An alluvial diagram is a Sankey diagram whose columns show the same categories at different times, to show how items move between them. A chord diagram arranges the groups round a circle, which suits flows that go in both directions between the same groups.
Common Sankey diagram mistakes
- Flows that don't balance. If a middle node takes in more than it sends out, readers can't tell whether something is missing. Show losses, storage or "other" as their own bands and nodes.
- Too many nodes and hair-thin bands. A diagram with dozens of tiny links is hard to read. Group the smallest flows into one "Other" link, or split the diagram in two.
- Too many crossings. Order the nodes in each column so bands run mostly straight across. Moving one node up or down a column can remove several crossings.
- Flows that loop back. A Sankey diagram runs one way, from left to right. If something returns to an earlier stage (recycling, for example), show it as a separate node in a later column rather than a band that runs backwards.
- Mixed units. Every band must use the same unit. Don't mix tonnes with dollars, or energy in different units, in one diagram.
- Colour that means nothing. Colour bands by their source or by the type of flow, and say which. Random colours make paths harder to follow.
How to create a Sankey diagram in JavaScript, React or Angular
SciChart.js has no separate Sankey series, but its triangle series can fill any shape, so a short layout helper turns your nodes and links into bars and bands. Because SciChart.js draws with WebGL and WebGPU, the diagram stays smooth to zoom and pan. Try the diagram below: hover over a band or node to highlight its path and see its value, click to keep the highlight, scroll to zoom, drag to pan and double-click to reset.
Here is the code for this diagram. The data is plain JSON: a list of nodes, and a list of links with a source, a target and a value:
{
"nodes": [{ "id": "gas", "name": "Natural gas", "color": "#F48420" }, { "id": "electricity", "name": "Electricity", "color": "#50C7E0" }],
"links": [{ "source": "gas", "target": "electricity", "value": 22 }]
}
- JavaScript
- React
- Angular
// Create a JavaScript Sankey diagram with SciChart.js: node bars and curved flow bands drawn as triangles
const {
SciChartSurface,
NumericAxis,
NumberRange,
XyDataSeries,
FastTriangleRenderableSeries,
ETriangleSeriesDrawMode,
NativeTextAnnotation,
EHorizontalAnchorPoint,
EVerticalAnchorPoint,
EMultiLineAlignment,
Thickness,
CustomChartModifier2D,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier,
SciChartJsNavyTheme
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"
// 1. LAYOUT HELPER (plain JavaScript, no SciChart code)
// Takes { nodes: [{ id, name, color, column? }], links: [{ source, target, value }] } and works out where
// every node bar and flow band goes, in a box `width` x `height` with y = 0 at the bottom.
function computeSankeyLayout(data, options) {
const {
width = 1000,
height = 600,
nodeWidth = 24, // thickness of each node bar
nodePadding = 24, // vertical gap between bars in a column
curveSteps = 40 // how many slices each curved band is cut into
} = options || {};
const nodes = data.nodes.map((node, index) => ({
...node,
index,
column: 0,
valueIn: 0,
valueOut: 0,
value: 0,
x0: 0,
x1: 0,
y0: 0, // top of the bar (measured down from the top of the box while laying out)
y1: 0, // bottom of the bar
sourceLinks: [] as any[], // links leaving this node
targetLinks: [] as any[] // links arriving at this node
}));
const nodeById = new Map();
nodes.forEach((node) => nodeById.set(node.id, node));
const links = data.links.map((link, index) => {
const source = nodeById.get(link.source);
const target = nodeById.get(link.target);
if (!source || !target) throw new Error(`Unknown node in link ${link.source} -> ${link.target}`);
const layoutLink = { index, source, target, value: link.value, width: 0, sourceY: 0, targetY: 0, xValues: [] as number[], yValues: [] as number[] };
source.sourceLinks.push(layoutLink);
target.targetLinks.push(layoutLink);
source.valueOut += link.value;
target.valueIn += link.value;
return layoutLink;
});
// A node is as tall as the larger of what flows in and what flows out
nodes.forEach((node) => (node.value = Math.max(node.valueIn, node.valueOut)));
// Columns: each node goes one column to the right of its furthest-left source (longest path).
// A node can also set its own `column`.
for (let pass = 0; pass <= nodes.length; pass++) {
let changed = false;
links.forEach((link) => {
if (link.target.column < link.source.column + 1) {
link.target.column = link.source.column + 1;
changed = true;
}
});
if (!changed) break;
if (pass === nodes.length) throw new Error("The links form a loop: a Sankey diagram needs flows that only go forwards");
}
nodes.forEach((node) => {
const fixedColumn = data.nodes[node.index].column;
if (Number.isInteger(fixedColumn)) node.column = fixedColumn;
});
const lastColumn = Math.max(...nodes.map((node) => node.column));
const columns = Array.from({ length: lastColumn + 1 }, (_, column) => nodes.filter((node) => node.column === column));
// One scale for every column (value units -> layout units), set by the column that needs the most room
const scale = Math.min(
...columns.map((column) => {
const total = column.reduce((sum, node) => sum + node.value, 0);
return (height - (column.length - 1) * nodePadding) / total;
})
);
// Place the bars: columns spread evenly across the width, each column centred vertically
columns.forEach((column, columnIndex) => {
const columnHeight = column.reduce((sum, node) => sum + node.value * scale, 0) + (column.length - 1) * nodePadding;
let y = (height - columnHeight) / 2;
column.forEach((node) => {
node.x0 = lastColumn === 0 ? 0 : (columnIndex * (width - nodeWidth)) / lastColumn;
node.x1 = node.x0 + nodeWidth;
node.y0 = y;
node.y1 = y + node.value * scale;
y = node.y1 + nodePadding;
});
});
// Stack the bands on each bar, ordered by the position of the node at their other end, so fewer bands cross
nodes.forEach((node) => {
node.sourceLinks.sort((a, b) => a.target.y0 - b.target.y0);
node.targetLinks.sort((a, b) => a.source.y0 - b.source.y0);
let y = node.y0;
node.sourceLinks.forEach((link) => {
link.sourceY = y;
y += link.value * scale;
});
y = node.y0;
node.targetLinks.forEach((link) => {
link.targetY = y;
y += link.value * scale;
});
});
// Each band: an S-shaped curve from the source bar to the target bar, with a constant vertical thickness.
// Cut it into thin slices and list the top and bottom point of each slice, in turn. Drawn as a triangle strip,
// every three consecutive points make one triangle, so the points fill the band.
links.forEach((link) => {
link.width = link.value * scale;
const x0 = link.source.x1;
const x1 = link.target.x0;
for (let step = 0; step <= curveSteps; step++) {
const t = step / curveSteps;
const ease = t * t * (3 - 2 * t); // smoothstep: flat at both ends, steepest in the middle
const x = x0 + (x1 - x0) * t;
const top = link.sourceY + (link.targetY - link.sourceY) * ease;
link.xValues.push(x, x);
link.yValues.push(height - top, height - (top + link.width)); // flip so y = 0 is at the bottom
}
});
// Flip the bars too, so y = 0 is at the bottom, as on a chart axis
nodes.forEach((node) => {
const top = height - node.y0;
node.y0 = height - node.y1;
node.y1 = top;
});
return { nodes, links, width, height };
}
// 2. TURN THE LAYOUT INTO SCICHART SERIES
// One FastTriangleRenderableSeries per band and per bar, so each can be coloured, faded and hit-tested on its own.
function addSankeySeries(sciChartSurface, wasmContext, layout, options) {
const { linkOpacity = 0.45, units = "" } = options || {};
const items: { kind: string; data: any; series: any }[] = [];
layout.links.forEach((link) => {
const series = new FastTriangleRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues: link.xValues, yValues: link.yValues }),
drawMode: ETriangleSeriesDrawMode.Strip, // each point makes a triangle with the two before it
fill: link.source.color, // colour each band like the node it comes from
opacity: linkOpacity
});
sciChartSurface.renderableSeries.add(series);
items.push({ kind: "link", data: link, series });
});
layout.nodes.forEach((node) => {
// A bar is a rectangle: two triangles from four corner points
const series = new FastTriangleRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, {
xValues: [node.x0, node.x0, node.x1, node.x1],
yValues: [node.y1, node.y0, node.y1, node.y0]
}),
drawMode: ETriangleSeriesDrawMode.Strip,
fill: node.color
});
sciChartSurface.renderableSeries.add(series);
items.push({ kind: "node", data: node, series });
// Label: name and total, to the right of the bar (to the left in the last column)
const isLastColumn = node.x1 >= layout.width - 1;
sciChartSurface.annotations.add(
new NativeTextAnnotation({
x1: isLastColumn ? node.x0 - 8 : node.x1 + 8,
y1: (node.y0 + node.y1) / 2,
text: `${node.name}\n${node.value} ${units}`,
textColor: "#FFFFFF",
fontSize: 16,
horizontalAnchorPoint: isLastColumn ? EHorizontalAnchorPoint.Right : EHorizontalAnchorPoint.Left,
verticalAnchorPoint: EVerticalAnchorPoint.Center,
multiLineAlignment: isLastColumn ? EMultiLineAlignment.Right : EMultiLineAlignment.Left
})
);
});
// Fade everything except the focused band or bar and what it connects to. Pass null to show everything.
function highlight(focus) {
const activeLinks = new Set();
const activeNodes = new Set();
if (focus?.kind === "link") {
activeLinks.add(focus.data);
activeNodes.add(focus.data.source).add(focus.data.target);
} else if (focus?.kind === "node") {
activeNodes.add(focus.data);
[...focus.data.sourceLinks, ...focus.data.targetLinks].forEach((link) => {
activeLinks.add(link);
activeNodes.add(link.source).add(link.target);
});
}
items.forEach((item) => {
const isActive = item.kind === "link" ? activeLinks.has(item.data) : activeNodes.has(item.data);
if (item.kind === "link") item.series.opacity = !focus ? linkOpacity : isActive ? 0.85 : 0.12;
else item.series.opacity = !focus || isActive ? 1 : 0.35;
});
}
// Tooltip text for a band or a bar
function describe(item) {
const percent = (part, whole) => `${Math.round((part / whole) * 100)}%`;
if (item.kind === "link") {
const { source, target, value } = item.data;
return `${source.name} to ${target.name}\n${value} ${units} (${percent(value, source.value)} of ${source.name.toLowerCase()})`;
}
const node = item.data;
if (!node.targetLinks.length) return `${node.name}\n${node.valueOut} ${units} in total`;
if (!node.sourceLinks.length) return `${node.name}\n${node.valueIn} ${units} in total`;
return `${node.name}\nIn: ${node.valueIn} ${units} Out: ${node.valueOut} ${units}`;
}
// Bars are drawn on top of bands, so hit-test them first
const hitTestOrder = [...items].reverse();
return { items, hitTestOrder, highlight, describe };
}
// 3. HOVER, CLICK AND TOOLTIPS WITH SCICHART'S HIT-TEST API
// Each band and bar is its own triangle series, so series.hitTestProvider.hitTest(x, y) says whether the
// mouse is inside one of its triangles. Hover highlights and shows a tooltip; click keeps the highlight.
// CustomChartModifier2D is the base class for your own modifiers (ChartModifierBase2D with a ready-made type).
class SankeyHoverModifier extends CustomChartModifier2D {
sankey;
tooltip;
hovered = null;
selected = null;
mouseDownPoint: { x: number; y: number } | null = null;
constructor(sankey) {
super();
this.sankey = sankey;
this.tooltip = new NativeTextAnnotation({
text: "",
isHidden: true,
textColor: "#FFFFFF",
fontSize: 15,
background: "#0F1A2B",
multiLineAlignment: EMultiLineAlignment.Left,
padding: new Thickness(6, 10, 6, 10),
lineSpacing: 4,
verticalAnchorPoint: EVerticalAnchorPoint.Bottom
});
}
onAttach() {
super.onAttach();
this.parentSurface.annotations.add(this.tooltip);
}
onDetach() {
this.parentSurface?.annotations.remove(this.tooltip);
super.onDetach();
}
// Returns the topmost band or bar under the mouse, or null
hitTestSankey(mousePoint) {
for (const item of this.sankey.hitTestOrder) {
const hitTestInfo = item.series.hitTestProvider.hitTest(mousePoint.x, mousePoint.y);
if (hitTestInfo.isHit) return { item, hitTestInfo };
}
return null;
}
modifierMouseMove(args) {
super.modifierMouseMove(args);
const hit = this.hitTestSankey(args.mousePoint);
this.hovered = hit?.item ?? null;
if (hit) {
// Place the tooltip just above the mouse, flipped to the left near the right-hand edge
const { x, y } = hit.hitTestInfo.hitTestPointValues;
const xRange = this.parentSurface.xAxes.get(0).visibleRange;
const nearRightEdge = x > xRange.min + xRange.diff * 0.65;
this.tooltip.text = this.sankey.describe(hit.item);
this.tooltip.horizontalAnchorPoint = nearRightEdge ? EHorizontalAnchorPoint.Right : EHorizontalAnchorPoint.Left;
this.tooltip.x1 = x + xRange.diff * (nearRightEdge ? -0.012 : 0.012);
this.tooltip.y1 = y + this.parentSurface.yAxes.get(0).visibleRange.diff * 0.04;
}
this.tooltip.isHidden = !hit;
this.sankey.highlight(this.hovered ?? this.selected);
}
modifierMouseDown(args) {
super.modifierMouseDown(args);
this.mouseDownPoint = args.mousePoint;
}
modifierMouseUp(args) {
super.modifierMouseUp(args);
// A click, not the end of a drag to pan: select what was clicked, or clear the selection
const start = this.mouseDownPoint;
if (start && Math.hypot(args.mousePoint.x - start.x, args.mousePoint.y - start.y) < 5) {
const hit = this.hitTestSankey(args.mousePoint);
this.selected = hit && hit.item !== this.selected ? hit.item : null;
this.sankey.highlight(this.hovered ?? this.selected);
}
this.mouseDownPoint = null;
}
modifierMouseLeave(args) {
super.modifierMouseLeave(args);
this.hovered = null;
this.tooltip.isHidden = true;
this.sankey.highlight(this.selected);
}
}
// 4. THE CHART
async function sankeyDiagram(divElementId) {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(divElementId, {
theme: new SciChartJsNavyTheme()
});
// Your data: nodes and links, as JSON
const layout = computeSankeyLayout(getEnergyFlowData(), { width: 1000, height: 600 });
// The axes only set the drawing area. They're hidden: a Sankey diagram has no scales.
// Extra space at the bottom keeps the lowest bar clear of the chart's bottom-left corner.
sciChartSurface.xAxes.add(
new NumericAxis(wasmContext, { isVisible: false, growBy: new NumberRange(0.02, 0.02) })
);
sciChartSurface.yAxes.add(
new NumericAxis(wasmContext, { isVisible: false, growBy: new NumberRange(0.1, 0.03) })
);
const sankey = addSankeySeries(sciChartSurface, wasmContext, layout, { units: "TWh" });
// Hover for values, click to keep a flow highlighted, scroll to zoom, drag to pan, double-click to reset
sciChartSurface.chartModifiers.add(
new SankeyHoverModifier(sankey),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
}
import { SciChartReact } from "scichart-react";
import {
SciChartSurface,
NumericAxis,
NumberRange,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier,
SciChartJsNavyTheme
} from "scichart";
// computeSankeyLayout, addSankeySeries and SankeyHoverModifier from the JavaScript tab, saved as sankey.ts
import { computeSankeyLayout, addSankeySeries, SankeyHoverModifier } from "./sankey";
// initChart builds the chart; SciChartReact creates it, sizes it and cleans it up
const initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
// { nodes: [{ id, name, color }], links: [{ source, target, value }] }
const layout = computeSankeyLayout(getYourSankeyData(), { width: 1000, height: 600 });
sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { isVisible: false, growBy: new NumberRange(0.02, 0.02) }));
sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { isVisible: false, growBy: new NumberRange(0.1, 0.03) }));
const sankey = addSankeySeries(sciChartSurface, wasmContext, layout, { units: "TWh" });
sciChartSurface.chartModifiers.add(
new SankeyHoverModifier(sankey),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
return { sciChartSurface };
};
export const SankeyDiagram = () => (
<SciChartReact initChart={initChart} style={{ width: "100%", height: 500 }} />
);
import { Component } from "@angular/core";
import { ScichartAngularComponent } from "scichart-angular";
import {
SciChartSurface,
NumericAxis,
NumberRange,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier,
SciChartJsNavyTheme
} from "scichart";
// computeSankeyLayout, addSankeySeries and SankeyHoverModifier from the JavaScript tab, saved as sankey.ts
import { computeSankeyLayout, addSankeySeries, SankeyHoverModifier } from "./sankey";
@Component({
selector: "app-sankey-diagram",
standalone: true,
imports: [ScichartAngularComponent],
template: `<scichart-angular [initChart]="initChart" style="display: block; width: 100%; height: 500px"></scichart-angular>`
})
export class SankeyDiagramComponent {
// initChart builds the chart; scichart-angular creates it, sizes it and cleans it up
initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
// { nodes: [{ id, name, color }], links: [{ source, target, value }] }
const layout = computeSankeyLayout(getYourSankeyData(), { width: 1000, height: 600 });
sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { isVisible: false, growBy: new NumberRange(0.02, 0.02) }));
sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { isVisible: false, growBy: new NumberRange(0.1, 0.03) }));
const sankey = addSankeySeries(sciChartSurface, wasmContext, layout, { units: "TWh" });
sciChartSurface.chartModifiers.add(
new SankeyHoverModifier(sankey),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
return { sciChartSurface };
};
}
Key points:
computeSankeyLayoutis plain JavaScript with no SciChart code, so you can reuse it anywhere. It gives each node a column, sets one scale for the whole diagram, stacks the links on each node, and lists the points of each curved band. It throws an error if the links form a loop.- Each band and each node bar is a FastTriangleRenderableSeries with
drawMode: ETriangleSeriesDrawMode.Strip: the points go top, bottom, top, bottom along the band, and every three in a row make a triangle. One series per shape lets each one have its own colour and opacity. - Hover and click use the series' hit-test API:
series.hitTestProvider.hitTest(x, y)returnsisHit: truewhen the mouse is inside one of that series' triangles, so no geometry code of your own is needed.SankeyHoverModifierextendsCustomChartModifier2D(custom chart modifiers) to run it on every mouse move. - Labels and the tooltip are NativeTextAnnotations. The axes are hidden, but they still set the drawing area, so zoom and pan work as on any chart.
See it in the demo app: JavaScript triangle series chart · React triangle series chart · Angular triangle series chart
Go deeper: SciChart.js triangle series documentation, including the strip, list and polygon draw modes, and the SciChart.js hit-test API documentation.
Frequently asked questions
What is a Sankey diagram used for?
A Sankey diagram is used to show where a total comes from and where it ends up, when something moves through stages. Typical examples are energy from fuels to end uses and losses, a budget from income to spending, materials through a factory, and people through a sign-up or hiring process. It makes the largest flows, and the biggest losses, easy to spot.
What do Sankey diagrams tell us?
A Sankey diagram tells you how a quantity is split and recombined on its way through a system: which sources contribute most, which paths carry the most, and how much reaches each end point. Because each band's width matches its value, you can see at a glance which flows dominate and where a large share is lost.
Why is it called a Sankey diagram?
It is named after Captain Matthew Henry Phineas Riall Sankey, an Irish engineer who in 1898 drew one to show where the heat supplied to a steam engine went, with each band's width matching the amount of energy. Flow drawings with widths in proportion to quantity are older: Charles Minard's 1869 map of Napoleon's march on Moscow is a famous example.
What is the difference between a Sankey diagram and an alluvial diagram?
An alluvial diagram is a kind of Sankey diagram. Its columns are usually the same set of categories measured at different times or by different groupings, and its bands show how items move between categories from one column to the next. A general Sankey diagram has different nodes in each column, such as fuels, then conversion, then end uses, and can show losses leaving the system.
How do I make a Sankey diagram in JavaScript?
Store the data as nodes and links, where each link has a source, a target and a value. A layout step gives each node a column and a height, stacks the links on each node, and turns every link into an S-shaped band. With SciChart.js you draw each band and bar as a FastTriangleRenderableSeries in triangle-strip mode, and use the series' hit-test to add hover highlights and tooltips. The same code works in React with scichart-react and in Angular with scichart-angular.
Sources
- Kennedy, A. B. W. and Sankey, H. R. (1898), The thermal efficiency of steam engines. Minutes of the Proceedings of the Institution of Civil Engineers, 134, 278–312. The committee report that included Sankey's energy-flow diagram of a steam engine.
- Schmidt, M. (2008), The Sankey diagram in energy and material flow management, Part I: History. Journal of Industrial Ecology, 12(1), 82–94. The history of the diagram and how its use spread from engineering to energy and material accounts.
- Schmidt, M. (2008), The Sankey diagram in energy and material flow management, Part II: Methodology and current applications. Journal of Industrial Ecology, 12(2), 173–185. How Sankey diagrams are used for energy and material flow accounts.