Plotly to_html()输出在Jupyter Notebook及nbconvert导出中无法正常显示
问题
使用Plotly的to_html()方法将图表转为HTML后,通过display(HTML(x))在JupyterLab中可正常显示,但在Jupyter Notebook中无任何内容显示。此外,使用nbconvert将JupyterLab笔记本导出为HTML时,生成的HTML文件中Plotly图表也无法正常渲染(但在JupyterLab内可正常显示)。
复现代码
import plotly.graph_objs as go from IPython.display import HTML, display x = [1, 2, 3, 4, 5] y = [1, 4, 9, 16, 25] trace = go.Scatter(x=x, y=y) fig = go.Figure(data=[trace]) html_fig = fig.to_html() display(HTML(data=html_fig))
环境版本
- JuypterLab = 3.6.3
- Notebook = 6.5.4
- Python = 3.10.13
- plotly = 5.9.0
- IPython = 8.15.0
- nbconvert = 6.5.4
已尝试无效方法
- 显式设置Plotly渲染器为
notebook - 将HTML包裹在iframe中
- 导入Holoviews并启用Plotly扩展
- 初始化Plotly离线连接模式
解决方案
1. 直接使用Notebook渲染器显示图表
无需将图表转为HTML字符串,直接调用fig.show()并指定notebook渲染器,Plotly会自动处理Notebook环境的依赖加载:
import plotly.graph_objs as go x = [1,2,3,4,5] y = [1,4,9,16,25] trace = go.Scatter(x=x, y=y) fig = go.Figure(data=[trace]) # 针对Jupyter Notebook环境直接渲染 fig.show(renderer="notebook")
2. 生成包含Plotly.js的HTML
如果必须使用to_html(),需通过include_plotlyjs参数确保Plotly.js资源被嵌入或引用,避免因外部资源加载受限导致图表无法显示:
# 方法1:嵌入完整Plotly.js(无需联网,HTML文件体积较大) html_fig = fig.to_html(include_plotlyjs=True) display(HTML(html_fig)) # 方法2:引用CDN版Plotly.js(文件体积小,需要联网) html_fig = fig.to_html(include_plotlyjs="cdn") display(HTML(html_fig))
3. 修复nbconvert导出HTML的渲染问题
nbconvert导出时需要确保Plotly的依赖资源被正确注入,可通过plotly.offline模块的方法配合执行导出:
from plotly.offline import init_notebook_mode, iplot init_notebook_mode(connected=True) # 预加载Plotly.js资源 x = [1,2,3,4,5] y = [1,4,9,16,25] trace = go.Scatter(x=x, y=y) fig = go.Figure(data=[trace]) # 使用iplot显示,nbconvert导出时会保留渲染所需资源 iplot(fig)
导出时添加--execute参数确保所有输出被正确生成:
jupyter nbconvert --to html --execute PlotlyToHtml.ipynb
无效方法说明
- 设置
pio.renderers.default="notebook"需配合fig.show()使用,单独设置后用display(HTML)仍无法触发正确的渲染逻辑 - iframe方法因srcdoc内容的引号转义问题,容易导致HTML解析失败
- Holoviews扩展需要额外配置才能适配Plotly的nbconvert导出,仅导入扩展无法解决问题
init_notebook_mode(connected=True)需配合iplot而非display(HTML)才能生效
内容的提问来源于stack exchange,提问作者Enrico88
相关产品推荐
相关产品推荐

