隐藏 plotly sankey 节点和链接,同时保留总节点值

Hide plotly sankey nodes and links while preserving total node value

我想隐藏特定节点(在我的例子中是最右边的节点),同时保留中间节点的大小。举个简单的例子:

import plotly.graph_objects as go

link_data = dict(
    source = [0,1,1],
    target = [1,2,2],
    value = [1,1,1]
)

node_data = dict(
    label = ['a','b','c'],
)

fig = go.Figure(
    data = [go.Sankey(
        node = node_data,
        link = link_data
    )]
)
fig.show()

结果:

但我想要更像这样的东西:

我尝试过的一些方法:

-Python 3.8,剧情 5.3.1

  • 重新使用此方法创建 sankey
  • 我使用了一种稍微复杂一些的方法,类似于您的第二种方法。正如您所指出的,这意味着两件事
    1. 图表右边有space
    2. 悬停信息仍然存在!
  • 已扩展示例数据以显示节点 d 不可见,并且它是一个没有流出的端节点
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import plotly.express as px

links = [
    {"source": "a", "target": "b", "value": 1},
    {"source": "b", "target": "c", "value": 1},
    {"source": "b", "target": "c", "value": 1},
    {"source": "b", "target": "d", "value": 1}
]

df = pd.DataFrame(links)
nodes = np.unique(df[["source", "target"]], axis=None)
nodes = pd.Series(index=nodes, data=range(len(nodes)))
invisible = set(df["target"]) - set(df["source"])

fig = go.Figure(
    go.Sankey(
        node={
            "label": [n if not n in invisible else "" for n in nodes.index],
            "color": [
                px.colors.qualitative.Plotly[i%len(px.colors.qualitative.Plotly)]
                if not n in invisible
                else "rgba(0,0,0,0)"
                for i, n in enumerate(nodes.index)
            ],
            "line": {"width": 0},
        },
        link={
            "source": nodes.loc[df["source"]],
            "target": nodes.loc[df["target"]],
            "value": df["value"],
            "color": [
                "lightgray" if not n in invisible else "rgba(0,0,0,0)"
                for n in df["target"]
            ],
        },
    )
)

fig