
Cléa Aumont
August 29, 2023

Chris Parmer
Updated October 23, 2026
Sankey Diagrams - A Complete Guide
TL;DR
- A Sankey diagram draws quantities flowing between stages as ribbons whose width is proportional to the flow, so you can see where a total comes from, how it splits and where it ends up.
- Sankey diagrams are also known as Sankey charts, and are similar to alluvial diagrams and parallel sets.
- Use one for money, energy, materials, funnels and people moving between states, whenever every unit moves from one category to another and the split at each stage is the story.
- Use a bar chart instead when values are close and need precise comparison, and a heatmap when every source connects to every target.
- Any coding agent can make one with Plotly in a minute. In Python it's go.Sankey(node=dict(label=...), link=dict(source=..., target=..., value=...)).
What is a Sankey diagram?
Sankey diagrams look like this:

Data: Apple Form 10-K for fiscal 2024, SEC EDGAR.
How do you read a Sankey diagram? In the example above, notice these things:
- Each vertical bar is a node, an amount of money at one stage of the income statement, and each ribbon is a flow whose width is the money moving along it. The iPhone ribbon on the left is the widest of the five because iPhone brought in about half of Apple's revenue.
- Money moves from left to right, and whatever flows into a node flows back out of it. That's why the Revenue bar is exactly as tall as the five product bars stacked together, and why you can follow any dollar to where it ends up on the right.
- Color shows what kind of money each flow is. Blue is revenue, red is money spent on costs, expenses and taxes, and green is what's left as profit, so you can trace the green path from gross profit down to net income.
- Links can skip columns. The thin green line from Other income at the bottom left goes straight to Pretax income, and at $269M it would be easy to miss without its label.
- The curves and the up-and-down order of the nodes are only layout, because Plotly arranges the nodes to keep ribbons from crossing. Judge a flow by its width against the node it leaves, such as Cost of sales taking more than half of the Revenue bar.
It's often used for charts like these:

A budget. Taxes and borrowing flow into $6.75 trillion of fiscal 2024 federal spending, and the red ribbon shows that borrowing paid for 27% of it. Data: US Treasury, Monthly Treasury Statement, September 2024.

Energy and materials. Of the 32.8 quadrillion Btu that went into US power plants in 2024, 59% was lost as heat before it reached a customer. Data: US EIA, Monthly Energy Review.

A funnel. Of 133,368 sessions on Google's merchandise store in December 2020, 79% never opened a product page and 1.6% ended in a purchase, and the purple loop shows shoppers who went back to browse after adding to their cart. Data: Google Analytics 4 sample e-commerce dataset.
A short history
The chart is named after Matthew Henry Phineas Riall Sankey, an Irish engineer who used one in an 1898 report on the thermal efficiency of steam engines to show how much of an engine's energy was lost at each step. The idea is older: Charles Minard's 1869 map of Napoleon's march on Moscow draws the army as a band whose width is the number of soldiers still alive, as Michael Friendly (2002) describes in his history of Minard's work.

Energy engineers kept drawing Sankeys for the next century, which is why national energy flow charts like the one above still look the way they do.
Alternatives to a Sankey diagram
Here's the same set of Titanic passengers drawn six ways. Some are better for the question, some worse, some just different:

- Grouped bar chart (better for precise comparisons). If the question is who survived, compare the rates directly: 97% of first-class women survived against 15% of men in second and third class. Bars on a shared baseline are easier to compare than ribbon widths, but they lose the sense of how many people were in each group.
- Parallel categories (works too, when every record has every field). It draws the same paths from the raw columns and lets readers drag categories to reorder them, so it's the Sankey's closest cousin. It can't show links that skip a column or loops.
- Heatmap (better for big origin-destination tables). A grid of rates or counts is compact and easy to look up, and it scales to dozens of categories on each side, where a Sankey turns into spaghetti. See our heatmap guide.
- Sunburst (different). It shows the same split as part of a whole, ring by ring, but can't show flows that merge again. See our sunburst chart guide.
- Icicle (different). The sunburst unrolled into columns reads left to right like a Sankey, but every column must add up exactly to its parent, so it can't show merges, loops or links that skip a level. See our icicle chart guide.
Two more alternatives fit other kinds of flow data. A waterfall chart (better for exact running totals) is the finance team's favorite chart for an income statement, because the amounts are easy to read, but it loses which revenue line paid for what. See our waterfall chart guide.

A funnel chart (better for simple drop-off rates) gives you clean step-by-step conversion, but it can't show which channel shoppers came from, where each group left, or the shoppers who looped back from the cart. See our funnel chart guide.

How to make a Sankey diagram
With AI
ChatGPT, Claude Code, GitHub Copilot, Cursor and other AI tools are excellent at writing Plotly code. Name Plotly in the prompt, spell out the columns, the stages and how links should be colored, and ask it to check that the flows balance:
Make a plotly Sankey diagram from orders.csv (columns: store, country, orders).- Add a middle column that splits Domestic (Canada) from International.- Keep the top 4 international countries and fold any others into "Other countries".- One color per store; color each link by its store at 45% opacity.- Show the total on every node label, e.g. "Yarnly 58".- Use the Inter font, a white background and a title that states the main takeaway.- Make sure inflow equals outflow at every node and print any node where it doesn't.- Save it as sankey.html and as a PNG at 2x scale.
The line about inflow and outflow is worth keeping in every Sankey prompt, because it catches the most common bug: a join or a filter that silently drops rows between columns.
With Plotly Studio
Plotly Studio is a product for creating data visualizations and Dash apps and for analyzing data with AI, available as a desktop app or embedded in Dash apps. Ask for a Sankey the same way:
Show a Sankey of Titanic passengers from class to sex to age group to survived or died. Color every link by whether the passenger survived and put the passenger count and survival rate on every node. Add a dropdown that switches the coloring from outcome to class.
Make a Sankey chart in Python or JavaScript
This is the code AI tools write under the hood. In Python, go.Sankey takes a list of node labels and three lists for the links: source and target are positions in the label list, and value sets each link's width:
import plotly.graph_objects as gofig = go.Figure(go.Sankey(node=dict(label=["Search", "Email", "Visited site", "Signed up", "Left"]),link=dict(source=[0, 1, 2, 2], # index into node.labeltarget=[2, 2, 3, 4],value=[60, 30, 35, 55],),))fig.show()
Real data usually arrives as a table with one row per path (class, sex, outcome, count), not as index lists. This helper turns that table into a Sankey. It prefixes node ids with the column name, so a value that appears in two columns (like "Other") becomes two nodes instead of a loop, and it can split links by a column so ribbons keep their color across every hop:
import pandas as pdimport plotly.graph_objects as godef rgba(hex_color, alpha):h = hex_color.lstrip("#")return f"rgba({int(h[:2], 16)}, {int(h[2:4], 16)}, {int(h[4:], 16)}, {alpha})"def sankey_from_paths(df, steps, value, color_by=None, colors=None, link_alpha=0.45):hops = []for a, b in zip(steps, steps[1:]):keys = [a, b] + ([color_by] if color_by and color_by not in (a, b) else [])hop = df.groupby(keys, as_index=False, sort=False)[value].sum()hops.append(hop.assign(src=a + ":" + hop[a].astype(str), tgt=b + ":" + hop[b].astype(str)))links = pd.concat(hops, ignore_index=True)nodes = list(dict.fromkeys(links["src"].tolist() + links["tgt"].tolist()))idx = {n: i for i, n in enumerate(nodes)}names = [n.split(":", 1)[1] for n in nodes]totals = [max(links.loc[links.src == n, value].sum(), links.loc[links.tgt == n, value].sum()) for n in nodes]link_colors = Noneif color_by:colors = colors or {}link_colors = [rgba(colors.get(k, "#a3a29b"), link_alpha) for k in links[color_by]]return go.Figure(go.Sankey(node=dict(label=[f"{name} {total:,}" for name, total in zip(names, totals)],color=[(colors or {}).get(name, "#3d3c39") for name in names],pad=20, thickness=12, line=dict(width=0),),link=dict(source=links["src"].map(idx), target=links["tgt"].map(idx),value=links[value], color=link_colors),))paths = pd.DataFrame({"channel": ["Search", "Search", "Email", "Email"],"plan": ["Free", "Pro", "Free", "Pro"],"outcome": ["Churned", "Retained", "Retained", "Retained"],"users": [120, 80, 40, 60],})fig = sankey_from_paths(paths, ["channel", "plan", "outcome"], "users",color_by="outcome", colors={"Retained": "#008300", "Churned": "#e34948"})fig.show()
In JavaScript, plotly.js takes the same node labels and link lists:
<div id="chart"></div><script src="https://cdn.plot.ly/plotly-4.1.1.min.js"></script><script>Plotly.newPlot("chart", [{type: "sankey",node: {label: ["Search", "Email", "Visited site", "Signed up", "Left"], pad: 20, thickness: 12},link: {source: [0, 1, 2, 2],target: [2, 2, 3, 4],value: [60, 30, 35, 55]}}]);</script>
To use the same Sankey chart in React, install react-plotly.js (npm install react-plotly.js plotly.js) and pass the same data and layout to its <Plot> component.
Share it
Every Plotly chart has a Share chart button (the cloud icon in its toolbar) that uploads it to Plotly Cloud and gives you a link. Only you can see it until you change its visibility.
For a live app, put the chart in a Dash app and publish it with the Plotly Cloud CLI. Coding agents can run these commands for you:
pip install "dash[cloud]"plotly user loginplotly app publish
If your data has to stay in your own cloud or data center, publish to Dash Enterprise instead.
Dos and don'ts
Most Sankeys that don't work have too many nodes connected to too many other nodes, or labels that leave the reader guessing. Here are the 660 science Nobel prizes (physics, chemistry, and physiology or medicine) awarded to laureates with an affiliation, by country of birth and country of affiliation, drawn both ways with the same colors.
Don't link every birth country to every award country, force a label onto dozens of thin nodes so they overlap, leave the totals off and use a serif font:

Do fold the long tail into "Other", add a middle step that splits laureates who stayed home from those who moved abroad, and put the total on every label:

Color the links for one question
Node colors name the categories, so the link colors are free to answer a question. Here are four options for the same 1,309 Titanic passengers, and each one is right for a different question.
By source. Shows where each flow comes from, here how each class splits by sex.

By target. Shows where each flow goes, here what share of each group survived.

By final outcome. Traces survivors and the dead back through every column, which needs links split by outcome on every hop.

Gray with one highlight. Follows one group, here the 709 third-class passengers, through the whole chart.

Checklist
Do
- Check that inflow equals outflow at every node, and make losses or borrowing their own node instead of letting widths change.
- Put the value on every node label, like Revenue<br>$391.0B.
- Write a title that states the takeaway, and say in the subtitle what the link colors mean.
- Use link opacity between 0.3 and 0.55, so overlapping ribbons stay readable.
- Order nodes on purpose, and pin them with node.x and node.y when the automatic layout tangles.
- Fold the tail into "Other". Five to eight nodes per column is plenty for a static chart.
- Leave out what doesn't move, such as people who stayed employed from one month to the next.
Don't
- Mix units, like dollars and percentages or users and sessions, in one diagram.
- Connect everything to everything. A complete bipartite graph is a heatmap pretending to be a Sankey.
- Give every node its own color when the colors mean nothing.
- Cram in more than about five columns or 30 nodes in a static chart.
- Use a Sankey to compare close values. Ribbon widths show "most of it goes here", not "41% or 44%".
Options to customize
These are the go.Sankey options that matter most. The full list is in the Plotly Sankey documentation and the Sankey reference.
- node.label: node names, with basic HTML like <b> and <br>. Put the value in the label.
- node.color: one color per node. Keep the same entity the same color in every column.
- node.thickness, node.pad: the width of the node bars and the gap between them. Increase pad when labels collide.
- node.align: justify (default), left, right or center. left stops dropouts at the stage where they left.
- node.x, node.y: manual positions from 0 to 1, to pin columns or fix a tangled layout.
- node.sort, link.sort: auto or input. input keeps nodes and links in the order you gave them, which untangles crossings.
- node.groups: lists of node indexes merged into one group node, for collapsing detail in an interactive chart.
- node.customdata, node.hovertemplate: custom hover text for nodes, like shares or notes.
- link.source, link.target, link.value: the flows, as node indexes and widths.
- link.color: one color per link, usually rgba() with transparency, to color by source, target, outcome or a highlight.
- link.hovercolor: the link color on hover.
- link.arrowlen: an arrowhead at the end of each link, for process flows where direction matters.
- link.customdata, link.hovertemplate: custom hover text for links, like the path attribute.
- link.colorscales: colors links by link.label with colorscales.
- arrangement: snap, perpendicular, freeform or fixed. Use fixed for published charts.
- orientation: h (default) or v, for top-down processes like clinical trial flow diagrams.
- valueformat, valuesuffix: the number format and unit in hover labels.
- domain: where the Sankey sits in the figure, for several Sankeys side by side.
- textfont: the label font, including shadow. Set shadow="none" on dark backgrounds.
More Sankey diagram examples
Ten more Sankeys built from real public data, each with its source, the technique that makes it work and a prompt to rebuild it.
1. Where the average US household's money goes, five levels deep

The "where does my paycheck go" chart, built for the average American household and taken five levels deep. $101,805 of income splits into taxes and take-home pay, then into spending buckets, BLS categories and line items, and housing alone takes $25,435, a quarter of pre-tax income. Data: BLS Consumer Expenditure Survey, 2023 (the bucket grouping is ours).
Tip: every node is pinned with node.x and node.y, so tax nodes and "Left over" stay in their own column instead of being pushed to the right edge, and each subcategory sits next to its parent.
Get the data from the BLS Consumer Expenditure Survey, all consumer units, 2023 (bls.gov/cex)and shape it into a table(columns: source, target, value, bls_code, note; US$ per household per year).The rows form a 5-level tree: income -> taxes/after-tax -> buckets -> categories -> subcategories.Build a plotly Sankey of where the average US household's money goes.- One color per bucket (Essentials, Insurance & pensions, Lifestyle, Giving & education,Left over), shared by everything downstream of it. Taxes in grays.- Pin node.x so each level gets its own column, and stack nodes so children sit besidetheir parent. End nodes like taxes and "Left over" must not jump to the last column.- Put the dollar amount on every label; make the figure about 1300x1000 so ~40 labels fit.- Assert that every parent equals the sum of its children.
Another way to see it: an icicle chart reads left to right like the Sankey and makes the line items easier to compare, but every column must add up exactly to its parent, so it can't show merges, loops or links that skip a level.

2. Who really pays for US health care

Insurers and government programs pay the hospital, and this chart adds the step that shows who gives them the money. Government funds 48% of America's $5.3 trillion health bill, and the federal government alone ($1.65T) puts in more than households do ($1.46T). Data: CMS National Health Expenditure Accounts, 2024.
Tip: only the funders get color, warm for private and cool for government; the payer-to-service half is neutral gray, and small services are grouped into seven so the right side stays readable.
Get the data from the CMS National Health Expenditure Accounts, 2024, Tables 5, 5-5, 5-6 and 19(cms.gov) and shape it into a table(columns: stage, source, target, value, year; US$ billions).Build a 4-column plotly Sankey: sector -> sponsor (who finances it) -> payer -> type of care.- Group the 12 services into ~7 (hospital; physicians & clinics; drugs & medical products;long-term care; dental; administration; research, buildings & public health).- Color sponsors warm (private) and cool (government); payer->service links neutral gray.- Order the service column to sit close to its biggest payers (long-term care near Medicaid).- Label every node with $B and % of the total.
3. Where methane comes from

Sector on the left, energy broken down by use in the middle, gas on the right. Everything is gray except methane, which makes up 19% of the 52 GtCO₂e of global emissions, so you can see where it comes from: farms, leaks from oil, gas and coal, and landfills. Data: Climate Watch via Our World in Data, 2023.
Tip: links can skip a column. Agriculture, waste and industry have no sub-sectors, so their ribbons go straight to the gases while energy stops to split.
Get the data from Climate Watch historical GHG emissions by sector and gas, World, 2023(via ourworldindata.org) and shape it into a table(columns: sector_group, sector, gas, value, year; MtCO2e).Build a plotly Sankey: sector group -> energy sub-sector -> gas. Groups without sub-sectors(agriculture, waste, industry, land use) link straight to the gases, skipping the middle column.- Make one variable HIGHLIGHT = "Methane (CH₄)". Color its links orange and everything else light gray.- Color a node orange when most of its emissions are the highlighted gas.- Order rows so methane-heavy sources sit on top next to the methane node.- Show GtCO2e on the labels and the highlighted gas's share of the total in the title.
Another way to see it: a sunburst of sector group, sector and gas is good for "what share of the total is this", but methane is scattered across several separate slivers, so "where does methane come from" is harder to answer than in the Sankey, where it all flows into one node.

4. The plastic loop that barely closes

Plastic is supposed to go round in circles, so this Sankey has a real loop: the green ribbon of recycled plastic leaves the far right and travels back to the start, where it becomes secondary plastic. Only 9% of 2019's 353 million tonnes of plastic waste made that trip. Data: OECD Global Plastics Outlook database, 2019.
Tip: a link whose target sits to the left of its source is drawn as a circular link around the diagram, and fixed node positions with one bright color make the loop the first thing you see.
Get the data from the OECD Global Plastics Outlook database, World, 2019 (OECD Data Explorer)and shape it into a table(columns: source, target, value; million tonnes).Build a plotly Sankey of the global plastic lifecycle with a recycling loop:virgin/secondary plastic -> plastics use -> applications -> added to stock / plastic waste-> landfilled / incinerated / mismanaged / recycled, and recycled -> secondary plastic.- The "Recycled -> Secondary plastic" link goes backwards, so plotly draws it as a loop.Pin every node with node.x/node.y (arrangement="fixed") so the loop runs cleanly under the chart.- Make the loop the only bright green element; everything else muted gray, with softorange/red for incinerated and mismanaged.- Show Mt on every label and the % of waste on each fate.
5. A clinical trial's participant flow, read top to bottom

CONSORT diagrams are the boxes-and-arrows chart every clinical trial publishes. Drawn as a vertical Sankey, the STEP 1 trial of semaglutide shows its 2:1 randomization of 1,961 participants and each arm's attrition: 95% of the semaglutide arm completed the trial against 93% on placebo. Data: ClinicalTrials.gov, NCT03548935.
Tip: orientation="v" gives a top-down read, and node.align="left" stops dropouts at the stage where they happened.
Get the data from the participant flow module of trial NCT03548935 on ClinicalTrials.gov(API v2) and shape it into a table(columns: source, target, value, arm; participants).Build a vertical plotly Sankey (orientation="v") of the trial's participant flow.- Randomized -> each arm -> Completed trial or Did not complete. Keep each arm's"Did not complete" as its own node, and put the dropout reasons in its hover text.- Semaglutide arm blue, placebo gray, completions green. Use node.align="left".- Show counts and completion rates on the labels. Make the figure square.
6. Who survived the Titanic

This Sankey follows all 1,309 passengers from the port where they boarded through class, sex and age to their fate, with every ribbon colored by whether that passenger survived. "Women and children first" jumps out: 73% of women survived and 19% of men. Data: titanic3 passenger list, Vanderbilt Biostatistics.
Tip: aggregate links by (source, target, outcome) instead of (source, target), so parallel ribbons keep their color through every hop. The helper function above does it for you.
Get the data from the titanic3 passenger list (hbiostat.org/data, Vanderbilt Biostatistics)and shape it into a table(columns: port, class, sex, age_group, outcome, count; all 1,309 passengers).Build a plotly Sankey: port -> class -> sex -> age group -> survived or died.- Color every link by the passenger's final outcome (blue survived, gray died),aggregating by (source, target, outcome) so colors carry through all five columns.- Put the passenger count and survival rate on every node, e.g. "Female 466 · 73% survived".- Keep classes in order 1st, 2nd, 3rd with node.sort="input".
7. The labor market churn under a steady unemployment rate

The unemployment rate barely moves from one month to the next, but about 15 million Americans changed labor force status between November and December 2024, and 4.3 million went straight from outside the labor force into a job. Data: BLS Current Population Survey labor force flows.
Tip: leave out the people who stayed put. 155 million employed people stayed employed, and including them would shrink every interesting ribbon to a hairline.
Get the data from the BLS Current Population Survey labor force status flows, seasonally adjusted,November to December 2024 (bls.gov/cps) and shape it into a table(columns: source, target, value, month; thousands of people).Build a plotly Sankey of labor force status changes from November to December 2024.- Keep only Employed, Unemployed and Not in labor force, and drop rows where the statusdidn't change (mention the stayers in the subtitle instead).- November on the left, December on the right, same order and color on both sides.- Show millions of people on every node and link hover.
8. Alaska's ranked-choice election, round by round

A results table tells you who won, and this shows how. Begich finished third in round 1, and his 53,810 ballots decided the race: 50% went to Palin, 29% to Peltola and 21% ranked neither, so Peltola won the final round with 51.5%. Data: Alaska Division of Elections, official RCV tabulation.
Tip: each candidate keeps one color in every round; transferred votes are bright and votes that stayed put are pale, so your eye goes straight to the transfers.
Get the data from the Alaska Division of Elections official ranked-choice tabulation for theAugust 2022 special general election (elections.alaska.gov) and shape it into a table(columns: round_from, candidate_from, round_to, candidate_to, votes).Build a plotly Sankey of the election, one column per round.- Each candidate keeps the same color in every round. Exhausted and inactive ballots are gray.- Links where the candidate changes (transfers) are bright; links where it stays the same are pale.- Use node.align="left" and label the columns "First choice", "Round 1", "Round 2".- Show vote counts and percentages on the node labels.
9. How US states voted, 2008 to 2024 (alluvial)

When the columns are time periods, a Sankey becomes an alluvial diagram. Across five elections there were only 19 state flips, and 40 of the 50 states and DC never changed party at all. Data: MIT Election Data and Science Lab.
Tip: pale ribbons for states that stayed and bright ribbons for flips. The flips are a small share of the width, so they need the brightest color on the page.
Get the data from the MIT Election Data and Science Lab US presidential results by state,1976-2024 (Harvard Dataverse) and shape it into a table(columns: year_from, party_from, year_to, party_to, states, electoral_votes_to).Build a plotly alluvial (Sankey) with one column per election: 2008, 2012, 2016, 2020, 2024.- Use the number of states as the link value. Democratic nodes blue, Republican red.- Links where the party stays the same are pale; flips use the destination party's color at full strength.- Keep Democratic on top in every column with fixed node.y positions and add year labels above each column.
10. Nobel laureates: born here, moved there

404 of 1,005 Nobel awards to individuals went to people at US institutions, and the middle column shows where they came from: 34% of those prizes went to people born somewhere else, with the UK, Germany and France the biggest named sources. Data: Nobel Prize API, all prizes through 2026.
Tip: a middle "stayed or moved" step turns a tangled country-to-country matrix into two clean bundles, and every ribbon keeps its birth country's color, bright for movers and pale for stayers.
Get the data from the Nobel Prize API v2.1 laureates endpoint (api.nobelprize.org)and shape it into a table(columns: id, name, year, category, birth_country, award_country; one row per award).Build a plotly Sankey: country of birth -> stayed or moved abroad -> country of affiliation.- Keep USA, United Kingdom, Germany, France, Japan and fold the rest into "Other".- Laureates with no affiliation stop in the middle column (use node.align="left").- Color every ribbon by birth country; movers bright (0.65), stayers pale (0.18).- Title: the share of prizes won at US institutions that went to people born abroad.
Another way to see it: an origin-destination heatmap scales to many more countries and every cell is easy to look up, with the diagonal holding everyone who stayed home, but you have to read the numbers to see how much of the US column is people born elsewhere.
