Sankey diagram in highcharts Python

Sankey diagram in highcharts Python

The amazing highcharts library includes Sankey diagrams. I use Python to create diagrams, typically in HEX notebooks (like Jupyter notebooks), so in this post we will work through a short example of creating a Sankey diagram in highcharts using Python.

Let’s begin by installing the library (from our Jupyter or HEX notebook).

# install highcharts-core using pip
!pip install highcharts-core        

Next, load the module:

# import catch-all .highcharts module.
from highcharts_core import highcharts        

Now we define some data that we will use for our chart, it has 3 dimensions, the from, the to, and the magnitude called weight. You’ll notice that each of the 4 from countries combines with each of the 4 to countries exactly once.

# define the data
my_iterable = [
    {'from': 'Brazil', 'to': 'Portugal', 'weight': 5},
    {'from': 'Brazil', 'to': 'France', 'weight': 1},
    {'from': 'Brazil', 'to': 'Spain', 'weight': 1},
    {'from': 'Brazil', 'to': 'England', 'weight': 1},
    {'from': 'Canada', 'to': 'Portugal', 'weight': 1},
    {'from': 'Canada', 'to': 'France', 'weight': 5},
    {'from': 'Canada', 'to': 'England', 'weight': 1},
    {'from': 'Mexico', 'to': 'Portugal', 'weight': 1},
    {'from': 'Mexico', 'to': 'France', 'weight': 1},
    {'from': 'Mexico', 'to': 'Spain', 'weight': 5},
    {'from': 'Mexico', 'to': 'England', 'weight': 1},
    {'from': 'USA', 'to': 'Portugal', 'weight': 1},
    {'from': 'USA', 'to': 'France', 'weight': 1},
    {'from': 'USA', 'to': 'Spain', 'weight': 1},
    {'from': 'USA', 'to': 'England', 'weight': 5}
]        

Finally we set up the chart and show it:

# set up the chart, feed the data, define the type
chart = highcharts.Chart(data = my_iterable, series_type = 'sankey')

# structure the series
chart.series = [{
    "keys": ["from", "to", "weight"],
    "data": my_iterable,
}]

# print chart 
# N.B.: do NOT use .display() after the object name (in HEX)
chart        

This should show a chart which responds to mouse hoover like so:

Article content
Sankey diagram, when hoovering over Portugal on the right-hand side


That’s it, let me know in the comments how it goes, if this is working and how you are using it.

Saptarshi 北斗 Masid (Sap)

Senior Designer | ex TATA Group, United Nations, WHO

9mo

Very useful and cool visualization method

Like
Reply

To view or add a comment, sign in

More articles by Bastiaan Quast PhD

Insights from the community

Others also viewed

Explore topics