Reputation: 389
Is the possible to matplotlib to create a sankey chart that style is like what plotly created?
Upvotes: 4
Views: 4039
Reputation: 1694
The Sankey chart using the D3Blocks library will create a d3.js chart but you can create it using Python!
Install first:
pip install d3blocks
# Load d3blocks
from d3blocks import D3Blocks
# Initialize
d3 = D3Blocks()
# Load example data
df = d3.import_example('energy')
# Plot
d3.sankey(df, filepath='sankey.html')
Upvotes: 0
Reputation: 412
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.
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()
Upvotes: 6