plotly - 将节点数添加到 Plotly Sankey 图

标签 plotly sankey-diagram plotly-python

我想向 Plotly Sankey 图 ( https://plot.ly/python/sankey-diagram/ ) 中的每个节点添加节点计数,使其看起来像红色箭头引用的计数。 enter image description here

这可能吗?我无法在 plotly 中找到这方面的例子。我上面提供的示例来自 R ( https://github.com/fbreitwieser/sankeyD3/blob/master/README.md ) 中的一个库,但我在 Python 中使用 plotly。

下面是我的代码。

import plotly.graph_objects as go
import pandas as pd

def plot_sankey(df, title):
    # Get column names
    cat_columns = [key for key, value in df.dtypes.iteritems() if value == 'O']

    # Mapping to unique values for categorical columns
    labels = pd.unique(df[cat_columns].values.ravel('K')).tolist()

    # Break dowmn each step
    final = []
    for i, row in df.iterrows():
        cat_values = row[cat_columns].values
        value = row['value']
        final.extend([(a, b, value) for a, b in zip(cat_values, cat_values[1:]) if a!=None and b!=None])

    # Build formatted version
    df_formatted = pd.DataFrame(final, columns=['source', 'target', 'value'])


    # Build Node
    node = dict(
              pad = 15,
              thickness = 20,
              line = dict(color = "black", width = 0.5),
              label = labels,
              color = "blue"
            )

    # Build Link
    link = dict(
              source = [labels.index(x) for x in df_formatted['source'].tolist()],
              target = [labels.index(x) for x in df_formatted['target'].tolist()],
              value = df_formatted['value'].tolist()
          )

    # Plot
    fig = go.Figure(data=[go.Sankey(node=node, link=link, visible=True)])
    fig.update_layout(title_text=title, 
                      font_size=10,
                      autosize=False,
                      width=2750,
                      height=1600)
    fig.show()

最佳答案

好像直接不行。但是,您通过

node = dict( label = ["A1", "A2", "B1", "B2", "C1"])

将显示在绘图上。

假设您可以预先计算每个节点的总数,您可以为每个节点传递一个具有名称和值的字符串,如下所示:

label = ["{} {}".format(node1_name, node1_val), "{} {}".format(node2_name, node2_val) ...]

或者,您可以在悬停中执行此操作。参见 here .

plotly sunburst 允许您通过“textinfo”属性很好地做到这一点,您可以在其中传递“label+value”——但这在 sankey 中不可用,因为 plotly 4.9 docs .

关于plotly - 将节点数添加到 Plotly Sankey 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59975614/

相关文章:

javascript - 在 div 中绘制 js 响应图

python - 在 Plotly Express 中使用 Pandas 索引

python - 使用绘图对象创建显示目录结构的树形图

python - 如何在按钮上添加单独的 Html 元素单击 Python Dash

r - Plotly 不显示线条

r - R中的桑基图 - 数据准备

python - 删除 Plotly Sankey 图中的文本标签,但悬停时保留数据 [Plotly Python Sankey 问题]

javascript - 为什么这个 d3 图表呈现十字,然后在移动节点时摆脱它们?

python - Plotly:如何组织下拉菜单?