matplotlib -可以创建一个普通的sankey图吗?

46scxncf  于 2022-11-15  发布在  其他
关注(0)|答案(2)|浏览(309)

matplotlib是否有可能创建一个风格与plotly创建的类似的sankey图表?

vfwfrxfs

vfwfrxfs1#

由于缺乏好的替代品,我咬紧牙关,尝试创建我自己的sankey图,看起来更像plotly和sankeymatic。这纯粹使用Matplotlib,并产生如下所示的流。我没有看到你的帖子中的plotly图像,所以我不知道你到底希望它看起来像什么。

完整的代码在底部。你可以用python -m pip install sankeyflow安装它。基本的工作流程很简单

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

请注意,pySankey也使用Matplotlib,但它只允许1个级别的双射流。SankeyFlow要灵活得多,有多个级别,不必是双射的,但需要您定义节点。

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()
yx2lnoni

yx2lnoni2#

使用D3Blocks库的Sankey图表将创建一个d3.js图表,但您可以使用Python创建它!
首先安装:

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')

相关问题