You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jupyter Notebook/Lab中Plotly offline.iplot输出桑基图时出现大片空白

解决Jupyter Notebook中Plotly Sankey图空白的问题

看到你遇到了代码无报错但Sankey图输出空白的问题,我帮你梳理几个最可能的原因和对应的解决办法:

1. 先补全link部分的value参数

你的代码里value = df['Value'].dropna(...)没写完,得补充完整的过滤参数,比如:

value = df['Value'].dropna(axis=0, how='any')

这虽然不一定是空白的直接原因,但不完整的代码可能隐藏其他潜在问题。

2. 核心问题:source和target必须是节点的索引值

Plotly Sankey图的source和target字段要求是节点在node.label列表中的索引位置,而不是节点名称本身。如果你的df['Source']和df['Target']存的是节点名称(和Node, Label列内容一致),必须先把它们转换成对应的索引,否则Plotly找不到对应节点,就会显示空白。

给你个转换的示例:

# 获取所有唯一的节点标签
unique_labels = df['Node, Label'].dropna().unique()
# 建立标签到索引的映射字典
label_to_idx = {label: idx for idx, label in enumerate(unique_labels)}
# 将Source和Target列转换为索引值
df['Source_idx'] = df['Source'].map(label_to_idx)
df['Target_idx'] = df['Target'].map(label_to_idx)

之后在link里改用转换后的索引列:

link = dict(
    source = df['Source_idx'].dropna(axis=0, how='any'),
    target = df['Target_idx'].dropna(axis=0, how='any'),
    value = df['Value'].dropna(axis=0, how='any')
)

3. 确认节点与链接数据的完整性

  • 确保node.label里的每个标签都是唯一的,没有重复项;
  • 检查转换后的Source_idx和Target_idx没有NaN值,否则对应的链接会被忽略,可能导致整张图无法正常渲染;
  • 确认Value列都是数值类型,没有混入非数值内容。

4. 完整的修正后代码示例

把以上要点整合起来,你的代码可以改成这样:

import numpy as np
import pandas as pd
import plotly as ply
ply.offline.init_notebook_mode(connected=True)

# 读取数据
df = pd.read_csv('C:\\Users\\a245401\\Desktop\\Test.csv', sep=';')
print(df.head())
print(ply.__version__)

# 处理节点标签与索引映射
unique_labels = df['Node, Label'].dropna().unique()
label_to_idx = {label: idx for idx, label in enumerate(unique_labels)}

# 转换Source和Target为索引值
df['Source_idx'] = df['Source'].map(label_to_idx)
df['Target_idx'] = df['Target'].map(label_to_idx)

# 构建Sankey图数据
data_trace = dict(
    type='sankey',
    domain = dict(
        x = [0,1],
        y = [0,1]
    ),
    orientation = "h",
    valueformat = ".0f",
    node = dict(
        pad = 10,
        thickness = 30,
        line = dict(
            color = "black",
            width = 0.5
        ),
        label = unique_labels,  # 使用去重后的节点标签
        color = df['Color'].dropna().unique()  # 确保颜色与节点一一对应
    ),
    link = dict(
        source = df['Source_idx'].dropna(axis=0, how='any'),
        target = df['Target_idx'].dropna(axis=0, how='any'),
        value = df['Value'].dropna(axis=0, how='any')
    )
)

# 设置布局并绘图
layout = dict(
    title = "Sankey Diagram Test",
    font = dict(
        size = 12
    )
)

fig = dict(data=[data_trace], layout=layout)
ply.offline.iplot(fig)

5. 其他排查点

  • 如果你的Plotly版本较旧(比如低于4.0),Sankey的参数格式可能有差异,建议升级到最新稳定版:pip install --upgrade plotly;
  • 检查浏览器是否有广告拦截插件,这类插件可能会阻止Plotly的JavaScript脚本加载,导致图不显示,可以尝试关闭拦截器或更换浏览器。

内容的提问来源于stack exchange,提问作者eirikdaude

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:15:23