python - plotly sankey 图数据格式

标签 python dataframe plotly sankey-diagram

plotly 库有一些漂亮的 sankey 图 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],

我想知道是否有一个 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"],
        },
    )
)

enter image description here

关于python - plotly sankey 图数据格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69463804/

相关文章:

python - 如何获取嵌套列的唯一元素的 value_counts()?

python - plot.ly python 图 url

R plotly : how to order pie chart?

python - 使用数组进行二维求和 - Python

python - Cassandra cqlsh "unable to connect to any servers"

python - 使用 PySCIPOpt 设置 MIP 终止间隙

python - OFFSET 不能为负

python - 在循环中按索引对列表中的元素求和

斯卡拉 Spark : How to create a RDD from a list of string and convert to DataFrame

r - 从 3d 图表创建视频