Sankey diagram in highcharts Python
Bastiaan Quast PhD
Building fully decentral comms & social media; self-contained Nostr clients ?? & mesh relays ?? (Λ)
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:
That’s it, let me know in the comments how it goes, if this is working and how you are using it.
Senior Designer | ex TATA Group, United Nations, WHO
8 个月Very useful and cool visualization method
Building fully decentral comms & social media; self-contained Nostr clients ?? & mesh relays ?? (Λ)
8 个月also on medium (no paywall): https://medium.qua.st/sankey-diagram-in-highcharts-python-02a2d161cfc1