Plotly:如何在桑基图中设置节点位置?

样本数据如下:


unique_list = ['home0', 'page_a0', 'page_b0', 'page_a1', 'page_b1', 

               'page_c1', 'page_b2', 'page_a2', 'page_c2', 'page_c3']

sources = [0, 0, 1, 2, 2, 3, 3, 4, 4, 7, 6]

targets = [3, 4, 4, 3, 5, 6, 8, 7, 8, 9, 9]

values = [2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2]

使用文档中的示例代码


fig = go.Figure(data=[go.Sankey(

    node = dict(

      pad = 15,

      thickness = 20,

      line = dict(color = "black", width = 0.5),

      label = unique_list,

      color = "blue"

    ),

    link = dict(

      source = sources,

      target = targets,

      value = values

  ))])


fig.show()

这将输出以下 sankey 图

http://img3.mukewang.com/633e8a750001af7a08350369.jpg

但是,我想在同一垂直列中获取以相同数字结尾的所有值,就像最左边一列的所有节点都以 0 结尾一样。我在文档中看到可以移动节点位置,但是我想知道是否有比手动输入 x 和 y 值更简洁的方法。任何帮助表示赞赏。



摇曳的蔷薇
浏览 731回答 1
1回答

HUH函数

在和 中go.Sankey()设置和调整 x和arrangement='snap'y 位置。以下设置将按要求放置您的节点。x=<list>y=<list>阴谋:请注意,此示例中未明确设置 y 值。一旦一个公共 x 值有多个节点,y 值将自动调整以使所有节点显示在相同的垂直位置。如果您确实想明确设置所有位置,只需设置arrangement='fixed'编辑:我添加了一个自定义函数nodify(),该函数将相同的 x 位置分配给具有共同结尾的标签名称,例如'0'in&nbsp;['home0', 'page_a0', 'page_b0']。现在,如果你作为一个例子改变page_c1你page_c2会得到这个:完整代码:import plotly.graph_objects as gounique_list = ['home0', 'page_a0', 'page_b0', 'page_a1', 'page_b1',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'page_c1', 'page_b2', 'page_a2', 'page_c2', 'page_c3']sources = [0, 0, 1, 2, 2, 3, 3, 4, 4, 7, 6]targets = [3, 4, 4, 3, 5, 6, 8, 7, 8, 9, 9]values = [2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2]def nodify(node_names):&nbsp; &nbsp; node_names = unique_list&nbsp; &nbsp; # uniqe name endings&nbsp; &nbsp; ends = sorted(list(set([e[-1] for e in node_names])))&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; # intervals&nbsp; &nbsp; steps = 1/len(ends)&nbsp; &nbsp; # x-values for each unique name ending&nbsp; &nbsp; # for input as node position&nbsp; &nbsp; nodes_x = {}&nbsp; &nbsp; xVal = 0&nbsp; &nbsp; for e in ends:&nbsp; &nbsp; &nbsp; &nbsp; nodes_x[str(e)] = xVal&nbsp; &nbsp; &nbsp; &nbsp; xVal += steps&nbsp; &nbsp; # x and y values in list form&nbsp; &nbsp; x_values = [nodes_x[n[-1]] for n in node_names]&nbsp; &nbsp; y_values = [0.1]*len(x_values)&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; return x_values, y_valuesnodified = nodify(node_names=unique_list)# plotly setupfig = go.Figure(data=[go.Sankey(&nbsp; &nbsp; &nbsp; arrangement='snap',&nbsp; &nbsp; &nbsp; node = dict(&nbsp; &nbsp; &nbsp; pad = 15,&nbsp; &nbsp; &nbsp; thickness = 20,&nbsp; &nbsp; &nbsp; line = dict(color = "black", width = 0.5),&nbsp; &nbsp; &nbsp; label = unique_list,&nbsp; &nbsp; &nbsp; color = "blue",&nbsp; &nbsp; &nbsp;x=nodified[0],&nbsp; &nbsp; &nbsp;y=nodified[1]&nbsp; &nbsp; ),&nbsp; &nbsp; link = dict(&nbsp; &nbsp; &nbsp; source = sources,&nbsp; &nbsp; &nbsp; target = targets,&nbsp; &nbsp; &nbsp; value = values&nbsp; ))])fig.show()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python