Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib - is it possible to create a normal sankey chart?

Tags:

matplotlib

Is the possible to matplotlib to create a sankey chart that style is like what plotly created?

like image 856
peace Avatar asked Oct 22 '25 00:10

peace


1 Answers

With a lack of good alternatives, I bit the bullet and tried my hand at creating my own sankey plot that looks more like plotly and sankeymatic. This uses purely Matplotlib and produces flows like below. I don't see the plotly image in your post though, so I don't know what you want it to look like exactly.

sankeyflow example

Full code at bottom. You can install this with python -m pip install sankeyflow. The basic workflow is simply

from sankeyflow import Sankey
plt.figure()
s = Sankey(flows=flows, nodes=nodes)
s.draw()
plt.show()

Note that pySankey does use Matplotlib too, but it only allows for 1 level of bijective flow. SankeyFlow is much more flexible, with multiple levels and doesn't have to be bijective, but requires you to define the nodes.

from sankeyflow import Sankey
import matplotlib.pyplot as plt

plt.figure(figsize=(20, 10), dpi=144)
nodes = [
    [('Product', 20779), ('Sevice\nand other', 30949)],
    [('Total revenue', 51728)],
    [('Gross margin', 34768), ('Cost of revenue', 16960)],
    [('Operating income', 22247), ('Other income, net', 268), ('Research and\ndevelopment', 5758), ('Sales and marketing', 5379), ('General and\nadministrative', 1384)],
    [('Income before\nincome taxes', 22515)],
    [('Net income', 18765), ('Provision for\nincome taxes', 3750)]
]
flows = [
    ('Product', 'Total revenue', 20779, {'flow_color_mode': 'source'}),
    ('Sevice\nand other', 'Total revenue', 30949, {'flow_color_mode': 'source'}),
    ('Total revenue', 'Gross margin', 34768),
    ('Total revenue', 'Cost of revenue', 16960),
    ('Gross margin', 'Operating income', 22247),
    ('Gross margin', 'Research and\ndevelopment', 5758), 
    ('Gross margin', 'Sales and marketing', 5379), 
    ('Gross margin', 'General and\nadministrative', 1384),
    ('Operating income', 'Income before\nincome taxes', 22247),
    ('Other income, net', 'Income before\nincome taxes', 268, {'flow_color_mode': 'source'}),
    ('Income before\nincome taxes', 'Net income', 18765), 
    ('Income before\nincome taxes', 'Provision for\nincome taxes', 3750),
]

s = Sankey(
    flows=flows,
    nodes=nodes,
)
s.draw()
plt.show()
like image 81
rileyx Avatar answered Oct 26 '25 11:10

rileyx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!