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

Jupyter Notebook中Plotly图表无法显示问题求助

Jupyter Notebook中Plotly图表空白无法显示的排查方案

问题描述

运行以下Plotly测试代码后,Jupyter Notebook仅显示空白输出:

import plotly.offline as pyo
import plotly.graph_objects as go

pyo.init_notebook_mode()

summary = {'text/csv': 2, 'application/json': 1}
summary = {'Apples': 30, 'Bananas': 45, 'Cherries': 25}

mimetypes = list(summary.keys())
counts = list(summary.values())

fig = go.Figure()

fig.add_trace(go.Bar(x=mimetypes, y=counts))

fig.update_layout(
    title='Fruit Count',
    xaxis_title='Fruit',
    yaxis_title='Count'
)

# Show plot
fig.show()

环境信息:

  • Python 3.12
  • 核心依赖:jupyter、plotly==5.22.0、pandas
  • 完整环境包含jupyterlab4.2.3、notebook7.2.1等包

排查与解决办法

1. 调整Plotly初始化与渲染参数

较新版本的Plotly中,init_notebook_mode需要显式配置连接参数,或者指定渲染器:

# 方法1:修改初始化代码
import plotly.offline as pyo
pyo.init_notebook_mode(connected=True)

# 方法2:调用show时指定渲染器
fig.show(renderer="notebook")

2. 安装/启用Plotly Jupyter扩展

Plotly在Jupyter中依赖widget扩展支持,执行以下命令修复:

# 安装基础widget包
pip install ipywidgets
# 启用Notebook扩展
jupyter nbextension enable --py widgetsnbextension
# Jupyter Lab用户额外执行(Lab 3.x+可跳过labextension命令,直接装jupyterlab-widgets)
pip install jupyterlab-widgets
jupyter labextension install @jupyter-widgets/jupyterlab-manager plotlywidget

3. 修复版本兼容性

Python 3.12属于较新版本,Plotly 5.22.0对其支持可能存在问题,两种解决路径:

  • 降级Python到3.11稳定版
  • 升级Plotly到最新兼容版本:
pip install --upgrade plotly

4. 浏览器端排查

  • 更换Chrome/Firefox等主流浏览器打开Notebook
  • 用无痕模式访问,避免缓存干扰
  • 按F12打开浏览器控制台,查看是否有JavaScript报错,定位具体渲染问题

5. 替换渲染方式(备选方案)

如果以上方法无效,可以改用静态图片或HTML导出:

# 导出为静态图片(需先安装kaleido)
pip install kaleido
fig.write_image("fruit_count.png")

# 或导出为可交互HTML
fig.write_html("fruit_count.html")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 07:54:54