You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Plotly(Python)绘制Sankey图链路重叠、第三列节点对齐问题咨询

解决方案
  • 方案1:调整内置排列模式(优先尝试,无需手动计算坐标)
    Plotly Sankey 默认的snap排列规则容易出现链路重叠,你只需要在go.Sankey配置中新增arrangement = "perpendicular"参数,即可优化布局逻辑减少重叠,同时可以适当调大pad参数增加同列节点间距,进一步缓解拥挤问题,修改后的核心配置如下:
fig = go.Figure(data=[go.Sankey(
# 新增这一行调整排列规则
arrangement = "perpendicular",
node = dict(
  pad = 15, # 从默认5调整为15,增加节点间距
  thickness = 10,
  line = dict(color = "black", width = 0.5),
  label = list(range(max(max(sources), max(targets)) + 1)), # 修正原代码label长度不匹配节点总数的问题
  color = "blue"
),
link = dict(
  source = sources,
  target = targets,
  value  = values
))])

如果perpendicular效果不符合预期,也可以尝试将arrangement的值改为freeform。

  • 方案2:仅自定义第三列节点Y坐标(灵活可控,计算成本极低)
    你不需要手动计算所有节点的坐标,只需要给需要调整的第三列节点指定Y值,其余节点的x、y属性都填None,Plotly会自动完成剩余节点的布局:
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]

# 计算总节点数
node_count = max(max(sources), max(targets)) + 1
# 初始化x、y数组,默认都为None,让Plotly自动布局
x = [None] * node_count
y = [None] * node_count

# 替换为你实际的第三列节点ID,按顶部对齐的需求给y赋值,值越小位置越靠上
third_col_nodes = [18,20,23,33] 
for idx, node_id in enumerate(third_col_nodes):
    # 按顶部对齐依次分配y坐标,间隔可以自己调整
    y[node_id] = 0.1 + idx * 0.2

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

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

内容的提问来源于stack exchange,提问作者Koen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 01:36:02