# Here’s How to use Sankey Diagrams for Data Visualization

Sreedevi Gattu 22 Sep, 2022

This article was published as a part of theÂ Data Science Blogathon.

## Introduction to Sankey Diagram for Data Visualization

Very often, we are in a situation where we would have to visualize how data flows between entities. For example, let’s take the case of how residents have migrated from one country to another within the UK. Here, it would be an interesting analysis to see how many residents have migrated from England to say Northern Ireland, Scotland, and Wales.

Image source

From this Sankey diagram visualization, it is apparent that more residents have migrated from England to Wales than to Scotland or to Northern Ireland.

## What is a Sankey diagram?

Sankey diagrams typically depict theÂ flowÂ of data from one entity (or node) to another.

The entity from/to where data flows is referred to as aÂ nodeÂ – the node where the flow originates is theÂ source node (e.g. England on the left-hand side) and where the flow ends is theÂ targetÂ node (e.g. Wales on the right-hand side). The source and target nodes are often represented as rectangles with a label.

The flow itself is represented by a straight or a curved path is called theÂ link. The width of the flow/link is proportional to the amount/quantity of flow. In the above example, the flow (i.e. migration of residents) from England to Wales is wider (more) than that from England to Scotland or Northern Ireland indicating more number of residents migrating to Wales than to the other countries.

The Sankey diagrams can be used to represent the flow of energy, money, costs, anything that has a notion of flow.

Minard’s classic diagram of Napoleon’s invasion of Russia is perhaps the most famous example of the Sankey diagram. This visualization using the Sankey diagram displays very effectively how the French army progressed (or dwindled?) on its way to Russia and back.

Image source

Now, let’s see how we can use pythonâ€™s plotly to plot a Sankey diagram.

## How to plot a Sankey diagram?

For plotting a Sankey diagram, letâ€™s use theÂ Olympics 2021 dataset. This dataset has details about the medals tally – country, total medals, and the split across the gold, silver, and bronze medals. Let’s plot a Sankey diagram to understand how many of the medals a country won are Gold, Silver, and Bronze.

#### A basic plot

We will use the plotly’s go interfaceÂ Sankey that takes 2 parameters â€“ nodes and links.

Note that all the nodes – source and target should have unique identifiers.

In this case,

• the SourceÂ would be the country. Let’s consider the top 3 countries (which are the USA, China and Japan) as the source nodes. Let’s mark these source nodes with the following (unique) identifiers, labels and colours
• 0: United States of America: green
• 1: People’s Republic of China: blue
• 2: Japan: orange
• the TargetÂ would be the Gold, Silver and Bronze medals. Let’s mark these target nodes with the following (unique) identifiers, labels and colours
• 3: Gold: gold
• 4: Silver: silver
• 5: Bronze: brown
• the LinkÂ (between the source and target nodes) would be the number of medals of each kind (Gold, Silver, Bronze). From each source, we will have 3 links originating and each one ending in the target – Gold, Silver and Bronze. So we will have a total of 9 links. The width of each of the links should be the number of Gold, Silver and Bronze medals. Let’s mark these links with the following source to target, values and colours
• 0 (USA) to 3,4,5 : 39, 41, 33
• 1 (China) to 3, 4, 5 :Â 38, 32, 18
• 2 (Japan) to 3,4,5 :Â 27, 14, 17

We will need to instantiate 2 python dict objects to represent the

• nodes (both source and target): with labels & colors as individual lists and
• links: source node, target node, value (width), and the color of the links as individual lists

and pass this to the plotly‘s go interfaceÂ Sankey.

Each index of the lists â€“ label, source, target, value, and color – corresponds to one node or link respectively.

```NODES = dict( # Â  Â 0 Â  Â  Â  Â  Â  Â  Â  Â  1Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  2Â  Â  Â  Â  3 Â  Â  Â  4 Â  Â  Â  Â  Â  5
label = ["United States of America", "People's Republic of China", Â  "Japan", "Gold", "Silver", "Bronze"],
color = ["seagreen", Â  Â  Â  Â  Â  Â  Â  Â  "dodgerblue",Â  Â  Â  Â  Â  Â  Â  Â  Â  "orange", "gold", "silver", "brown" ],)
LINKS = dict( Â  source = [Â  0,Â  0,Â  0,Â  1,Â  1,Â  1,Â  2,Â  2,Â  2], # The origin or the source nodes of the link
target = [Â  3,Â  4,Â  5,Â  3,Â  4,Â  5,Â  3,Â  4,Â  5], # The destination or the target nodes of the link
value =Â  [ 39, 41, 33, 38, 32, 18, 27, 14, 17], # The width (quantity) of the links
# Target Node:Â  Â  3-GoldÂ  Â  Â  Â  Â  4 -SilverÂ  Â  Â  Â  5-Bronze
color = Â  Â  [ Â  "lightgreen", Â  "lightgreen", Â  "lightgreen",Â  Â  Â  # Source Node: 0 - United States of America
"lightskyblue", "lightskyblue", "lightskyblue",Â  Â  # Source Node: 1 - People's Republic of China
"bisque", Â  Â  Â  "bisque", Â  Â  Â  "bisque"],)Â  Â  Â  Â  # Source Node: 2 - Japan
fig = go.Figure(data)
fig.show()```

Sankey diagram â€“ a basic plot

Here we have a very basic plot. But do you notice how the diagram is too wide and Silver appears before the Gold? Letâ€™s adjust the position of the nodes and the width.

#### Adjust the position of nodes and width of the diagram

Let’s add the x and y positions for the nodes to explicitly specify the positions of the nodes. The values should be between 0 and 1.

```NODES = dict( # Â  Â  Â  Â  Â  0 Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  1Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  2Â  Â  Â  Â  3 Â  Â  Â  4 Â  Â  Â  Â  Â  5
Â  Â  Â  Â  Â  Â  label = ["United States of America", "People's Republic of China", Â  "Japan", "Gold", "Silver", "Bronze"],
Â  Â  Â  Â  Â  Â  color = [Â  Â  Â  Â  Â  Â  Â  Â  "seagreen", Â  Â  Â  Â  Â  Â  Â  Â  "dodgerblue",Â  "orange", "gold", "silver", "brown" ],
Â  Â  Â  Â  Â  Â  x Â  Â  = [ Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  0,Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  0, Â  Â  Â  Â  0,Â  Â  0.5,Â  Â  Â  0.5,Â  Â  Â  0.5],
Â  Â  Â  Â  Â  Â  y Â  Â  = [ Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  0,Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  0.5, Â  Â  Â  Â  1,Â  Â  0.1,Â  Â  Â  0.5,Â  Â  Â  Â  1],)
fig = go.Figure(data)
fig.update_layout(title="Olympics - 2021: Country &Â  Medals",Â  font_size=16)
fig.show()```

With this, we get a compact diagram:

Sankey diagram â€“ node position adjusted

See below how the various parameters passed in the code map to the nodes and links in the diagram

Sankey diagram â€“ how code maps to diagram

Sankey diagram â€“ with default hover labels

Currently, the information displayed in the hover labels is the default text. When you hover on the

• nodes, the node name, the number of incoming flows, the number of outgoing flows and the total value is displayed. For instance,Â
• node United States of America has a total of 11 medals (=39 Gold + 41 Silver + 33 Bronze)
• node Gold hasÂ  a total of 104 medals (= 39 from theÂ  USA, 38 from China, 27 from Japan)
• links, the source node name and target node name and the value of the link is displayed. For instance, the link from the source node USA to the target node Silver has 39 medals.Â

Don’t you think the labels are too verbose? All these can be improved.

Let’s improve the format of the hover labels using the hovertemplate parameter

• For the nodes, since the hoverlabels are not giving any new information than what is already present, let’s take the hoverlabel off by passing an empty hovertemplate = ” “
• For the links, we can make the label concise in the format <country>-<medal type>
• For both the nodes and links, let’s have the values displayed with the suffix “Medals”. e.g 113 Medals instead of just 113. This can be achieved by using the update_traces function with appropriate valueformat and valuesuffix.

```NODES = dict( # Â  Â  Â  Â  Â  0 Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  1Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  2Â  Â  Â  Â  3 Â  Â  Â  4 Â  Â  Â  Â  Â  5
label = ["United States of America", "People's Republic of China", Â  "Japan", "Gold", "Silver", "Bronze"],
color = [Â  Â  Â  Â  Â  Â  Â  Â  "seagreen", Â  Â  Â  Â  Â  Â  Â  Â  "dodgerblue",Â  "orange", "gold", "silver", "brown" ],
x Â  Â  = [ Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  0,Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  0, Â  Â  Â  Â  0,Â  Â  0.5,Â  Â  Â  0.5,Â  Â  Â  0.5],
y Â  Â  = [ Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  0,Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  0.5, Â  Â  Â  Â  1,Â  Â  0.1,Â  Â  Â  0.5,Â  Â  Â  Â  1],
hovertemplate=" ",)```

```LINK_LABELS = []
for country in ["USA","China","Japan"]:
for medal in ["Gold","Silver","Bronze"]:
```LINKS = dict( Â  source = [Â  0,Â  0,Â  0,Â  1,Â  1,Â  1,Â  2,Â  2,Â  2], # The origin or the source nodes of the link
target = [Â  3,Â  4,Â  5,Â  3,Â  4,Â  5,Â  3,Â  4,Â  5], # The destination or the target nodes of the link
value =Â  [ 39, 41, 33, 38, 32, 18, 27, 14, 17], # The width (quantity) of the links
# Target Node:Â  Â  3-GoldÂ  Â  Â  Â  Â  4 -SilverÂ  Â  Â  Â  5-Bronze
color = Â  Â  [ Â  "lightgreen", Â  "lightgreen", Â  "lightgreen",Â  Â  Â  # Source Node: 0 - United States of America
"lightskyblue", "lightskyblue", "lightskyblue",Â  Â  # Source Node: 1 - People's Republic of China
"bisque", Â  Â  Â  "bisque", Â  Â  Â  "bisque"], Â  Â  Â  Â  # Source Node: 2 - Japan

```data = go.Sankey(node = NODES, link = LINKS)
fig = go.Figure(data)
fig.update_layout(title="Olympics - 2021: Country &Â  Medals",Â  font_size=16)
fig.update_traces( valueformat='3d', valuesuffix=' Medals', selector=dict(type='sankey'))
fig.update_layout(hoverlabel=dict(bgcolor="lightgray",font_size=16,font_family="Rockwell"))
fig.show()```

Sankey diagram â€“ with improved hover labels

#### Generalize for multiple nodes and levels

Nodes are referred to as source and target with respect to a link. A node that is a target for one link can be a source for another.

• The code can be generalized to handle all the countries in the dataset.
• We can also extend the diagram to another level to visualize the total number of medals across the countries.

## End Notes

We saw how Sankey diagrams can be used to represent flows effectively and how plotly python library can be to generate Sankey diagrams for a sample dataset.