plotly 桑基图数据格式化

plotly sankey graph data formatting

plotly 库有一些不错的桑基图 https://plotly.com/python/sankey-diagram/

但数据要求您传递 source/target 对的索引。

    link = dict(
      source = [0, 1, 0, 2, 3, 3], # indices correspond to labels, eg A1, A2, A1, B1, ...
      target = [2, 3, 3, 4, 4, 5],

我想知道是否有 API 来简单地传递这些对的命名列表?

links = [
    {'source': 'start', 'target': 'A', 'value': 2},
    {'source': 'A', 'target': 'B', 'value': 2},
...
]

这更符合 bokeh/holoviews 需要数据(但 sankey 不适用于自循环)

还有这个pysankey widget

所以我可以在不处理所有内容的情况下更接近我的数据框?

或者,是否有一种很好的 pythonic 方法可以将其转换为一行 :D

  • 结构显然是pandas数据帧构造函数格式
  • 从中创建一个数据框,加上节点的关键序列
  • 由此可以很简单地从中构建桑基图
import pandas as pd
import numpy as np
import plotly.graph_objects as go

links = [
    {'source': 'start', 'target': 'A', 'value': 2},
    {'source': 'A', 'target': 'B', 'value': 1},
    {'source': 'A', 'target':'C', 'value':.5}

]

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

go.Figure(
    go.Sankey(
        node={"label": nodes.index},
        link={
            "source": nodes.loc[df["source"]],
            "target": nodes.loc[df["target"]],
            "value": df["value"],
        },
    )
)