首页 > 解决方案 > Plotly Sankey:如何避免将所有节点自动放置到右侧?

问题描述

Plotly Sankeys 填满了所有可用空间。

如果一些“分支”有 3 个级别(Node 0 -> Node 1 -> Node 3)而其他只有两个(Node 0 -> Node 2),则最终节点(Node 2Node 3)垂直对齐到右侧。
我希望能够垂直对齐Node 1(不是Node 3!)和Node 2,如附件中的第二个图所示。

我很难以编程方式对齐所有节点,所以我想避免这种可能性。

即使在前一种不受欢迎的情况下,也会出现问题(Jupyter Lab 的代码):

import plotly.graph_objects as go

sources = [ 0,  0,  1,  1]
targets = [ 1,  2,  3,  4]
values  = [59, 30, 29, 30]

labels = ['Node 0', 'Node 1', 'Node 2', 'Node 3', 'Node 4']

link = dict(source=sources, target=targets, value=values)
node = dict(label=labels)
data = go.Sankey(link=link, node=node)
fig = go.Figure(data)
fig.show(renderer="svg", width=1000, height=500)

产生:

默认错误放置

放置节点 1时似乎有一个错误,没有考虑节点0-> 2流的厚度。

是否可以说我希望节点 2 在节点 1 的同一垂直线上,并且节点 2 没有子节点?一个解决方案是手动放置,可惜我不能这样做,因为我的 Sankey 是高度动态的。

作为一种解决方法,我在Node 2之后创建了一个虚拟节点,并使其不可见:

import plotly.graph_objects as go

sources = [ 0,  0,  1,  1, 2]
targets = [ 1,  2,  3,  4, 5]
values  = [59, 30, 29, 30, 30]
labels = ['Node 0', 'Node 1', 'Node 2', 'Node 3', 'Node 4']

color_links = ["lightgray", "lightgray", "lightgray", "lightgray", "white"]
color_nodes = ["red", "blue", "green", "navy", "lightgreen", "white"]

link = dict(source=sources, target=targets, value=values, color=color_links)
node = dict(label=labels, color=color_nodes, line = dict(width = 0))
data = go.Sankey(link=link, node=node)
fig = go.Figure(data)
fig.show(renderer="svg", width=1000, height=500)

这会产生:

笨拙的解决方法

我希望有一种更好、更简单的方法来做到这一点。是否有任何指向工作演示的指针?

标签: pythonplotly

解决方案


推荐阅读