绘制桑基图数据格式

dcs*_*san 3 python dataframe plotly sankey-diagram

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

但数据要求您传递源/目标对的索引。

    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],
Run Code Online (Sandbox Code Playgroud)

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

links = [
    {'source': 'start', 'target': 'A', 'value': 2},
    {'source': 'A', 'target': 'B', 'value': 2},
...
]
Run Code Online (Sandbox Code Playgroud)

这更符合bokeh/holoviews期望数据的方式 (但 sankey 不适用于自循环)

还有这个pysankey 小部件

这样我就可以更接近地映射到我的数据框而不处理所有内容?

或者,有没有一种很好的 Pythonic 方法可以将其转换为单行:D

Rob*_*ond 8

  • 该结构显然是pandas dataframe 构造函数格式
  • 从中创建一个数据框,加上节点的关键序列
  • 由此可以很容易地构建桑基图
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"],
        },
    )
)

Run Code Online (Sandbox Code Playgroud)

在此输入图像描述