Python中的Sankey图表

2024-05-19 20:54:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我非常想做一个类似链接中的例子:

How to add a label to each stratum to display additional information in a rank-change chart using alluvial in R?

我在Python中很难做到这一点,因为它创建了我不想要的多个链接figures。我的剧本是:

import plotly.graph_objects as go

fig = go.Figure(data=[go.Sankey(
    node = dict(
      pad = 15,
      thickness = 20,
      line = dict(color = "black", width = 0.5),
      label = ["A1", "A2", "A3", "A4", "A5", "A1", "A2", "A3", "A4", "A5"],
      color = "blue"
    ),
    link = dict(
      source = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], # indices correspond to labels, eg A1, A2, A1, B1, ...
      target = [2, 3, 4, 1, 5, 0, 9, 6, 7, 8],
      value = [8, 4, 2, 8, 4, 2,1, 0, 2, 3]
  ))])

fig.update_layout(title_text="Basic Sankey Diagram", font_size=10)
fig.show()

有人能帮我吗


Tags: toina2go链接a1figlabel
1条回答
网友
1楼 · 发布于 2024-05-19 20:54:47

由于您使用的是官方网站上的Sankey对话框,因此我将对其进行编辑,以显示ABs之间的数据结构。简单地说,源是A,目标是B,其余的是它的迭代。据我所知,问题中链接中显示的其他标签在plotly的sankey对话框中不可用。你必须对标签有创意。我将添加一个基于文本的解释我在做什么

import plotly.graph_objects as go

fig = go.Figure(data=[go.Sankey(
    node = dict(
      pad = 15,
      thickness = 20,
      line = dict(color = "black", width = 0.5),
      label = ["A1", "A2", "A3", "A4", "A5", "B1", "B2", "B3", "B4", "B5"], 
      color = "blue"
    ),
    link = dict(source = [0, 1, 2, 3, 4, 0, 1, 2, 3, 4],
                target = [5, 6, 8, 9, 7, 8, 6, 7, 9, 5], 
                value =  [8, 4, 3, 2, 6, 3 ,4 ,5, 2, 4] 
  ))])

fig.update_layout(title_text="Basic Sankey Diagram", font_size=10)
fig.show()

# Data structure
# labels  ->  A1 A2  A3  A4  A5  B1  B2  B3  B4  B5
# positon -> [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

# souce[0], value[0], target[0]
# [position](lables):[0]("A1") -> [8] -> [5]("B1")
# souce[1], value[1], target[1]
# [position](lables):[1]("A2") -> [4] -> [6]("B2")
# souce[2], value[2], target[2]
# [position](lables):[2]("A3") -> [3] -> [8]("B3")
...

enter image description here

相关问题 更多 >