首页 > 解决方案 > Plotly Sankey 图,对齐节点

问题描述

我使用 plotly (python) 创建了一个桑基图,它看起来像这样:

在此处输入图像描述

如您所见,一些链接重叠,但这个图可以很容易地(手动)更改为:

在此处输入图像描述

我认为重叠结果来自以 Y 为中心的第 3 列节点。有没有办法让我将第 3 列与顶部(或底部)对齐来解决这个问题?(当然也欢迎任何其他修复)

我发现的唯一一件事是手动为节点设置 x 和 y,但我似乎无法只设置 y,这也将涉及计算所有这些坐标。

感谢您的帮助!

编辑:我的代码

import plotly.graph_objects as go

sources = [23, 23, 23, 23, 23, 23, 23, 24, 8, 23, 23, 23, 30, 17, 5, 12, 20, 20, 23, 18, 18, 18, 18, 23, 33, 33, 33, 33, 33, 23, 16, 16, 23]
targets = [7, 13, 6, 21, 1, 2, 15, 23, 23, 32, 25, 19, 23, 23, 23, 23, 27, 22, 20, 31, 4, 0, 3, 18, 11, 26, 9, 14, 28, 33, 29, 10, 16]
values = [50.0, 1542.78, 287.44, 2619.76, 1583.26, 722.1, 5133.69, 6544.0, 2563.35, 6476.59, 4314.0, 82.87, 650.0, 1773.68, 16723.0, 32297.7, 81.64, 266.92, 348.56, 388.57, 743.2, 5403.24, 5821.52, 12356.53, 12905.68, 316.12, 497.68, 354.42, 3830.44, 17904.34, 175.95, 1224.46, 1400.41]

fig = go.Figure(data=[go.Sankey(
node = dict(
  pad = 5,
  thickness = 10,
  line = dict(color = "black", width = 0.5),
  label = list(range(len(values))),
  color = "blue"
),
link = dict(
  source = sources,
  target = targets,
  value  = values
))])

fig.update_layout(title_text=
"Basic Sankey Diagram", font_size=8)
fig.write_html("test.html")

标签: pythonplotlysankey-diagram

解决方案


github 上有一个未解决的问题,必须设置x和 y 位置才能使手动定位起作用。手动添加 y 坐标和 x 坐标是否可以解决您的问题?

一般来说,sankey排序还有其他问题

我只在 plotly.R 中处理这方面的问题,所以恐怕我无法提供具体的 python 建议来修改你的代码。

如果您还在寻找有关手动计算坐标的建议,您可以将其计算为

1 - (cumulative_sum_of_higher_nodes + current_node_size/2)

或者

1 - (cumulative_sum_of_all_nodes_including_current_node - current_node_size/2)

假设 y = 0 位于绘图区域的底部。


推荐阅读