如何在 plotly (python) sankey 中显示图例?

问题描述 投票:0回答:2

我想绘制一些桑基图来表示不同物质的质量流量以用于报告。我想用图例来区分物质,但我不知道该怎么做。我试过

showlegend
没有成功

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 = ['household','industry','waste'],
      color = "blue"
    ),
    link = dict(
      source = [0,1,0,1], # indices correspond to labels, eg A1, A2, A2, B1, ...
      target = [2,2,2,2],
      value = [7190,2074,4483,74.50],
      label = ['aluminium','aluminium','copper','copper'],
      color = ['#d7d6d6','#d7d6d6','#f3cf07','#f3cf07']
  ))])
fig.update_layout(showlegend=True)
fig.show() 

python plotly sankey-diagram
2个回答
5
投票

Plotly Sankey traces 似乎并不真正支持图例,尽管目前的文档似乎表明它们支持。

我已经在 Plotly 回购上创建了相应的问题;看起来该决议可能正在改进文档以使其更清晰。


0
投票

仍然没有官方支持,但您可以通过以下方式解决它:

  1. 为每个所需的图例条目创建虚拟轨迹
  2. 隐藏轴和绘图背景
  3. 显示图例
import plotly.graph_objects as go

colors = ["purple", "yellow", "yellow", "purple", "yellow", "yellow"]

sankey = go.Sankey(
    node=dict(color="blue"),
    link=dict(
        source=[0, 1, 0, 2, 3, 3],
        target=[2, 3, 3, 4, 4, 5],
        value=[8, 4, 2, 8, 4, 2],
        color=colors,
    ),
)

legend = []
legend_entries = [
    ["purple", "My Legend Text 1"],
    ["yellow", "My Legend Text 2"],
]
for entry in legend_entries:
    legend.append(
        go.Scatter(
            mode="markers",
            x=[None],
            y=[None],
            marker=dict(size=10, color=entry[0], symbol="square"),
            name=entry[1],
        )
    )

traces = [sankey] + legend
layout = go.Layout(
    showlegend=True,
    plot_bgcolor="rgba(0,0,0,0)",
)

fig = go.Figure(data=traces, layout=layout)
fig.update_xaxes(visible=False)
fig.update_yaxes(visible=False)
fig.show()

哪个应该给你这个: sankey+legend

© www.soinside.com 2019 - 2024. All rights reserved.