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

macOS M1下Jupyter Notebook中Plotly甘特图show()失效求助

解决M1 macOS下Jupyter Notebook中Plotly甘特图fig.show()无显示问题

核心问题分析

你遇到的情况是:Plotly通过figure_factory.create_gantt生成的图表,直接调用fig.show()无法渲染,但转为FigureWidget可以正常显示。这是因为当前Jupyter环境中Plotly的渲染后端配置存在问题,且官方已弃用jupyterlab-plotly扩展,需要改用新的渲染方式。

有效解决方案

方案1:强制指定Notebook渲染后端

在调用fig.show()前,手动设置渲染后端为notebook,覆盖默认配置:

import plotly.io as pio
pio.renderers.default = 'notebook'

# 修正原数据中的无效日期(2009-02-30不存在)
df = [dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Complete=10),
      dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15', Complete=60),
      dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30', Complete=95)]

fig = ff.create_gantt(df, colors='Blues', index_col='Complete',
               show_colorbar=True, bar_width=0.5,
               showgrid_x=True, showgrid_y=True)
fig.show()

方案2:用jupyter-dash替代旧扩展(官方推荐)

官方已弃用jupyterlab-plotly,改用jupyter-dash支持Jupyter环境的Plotly渲染,步骤如下:

  1. 安装依赖:
pip install jupyter-dash
  1. 修改代码适配渲染:
from jupyter_dash import JupyterDash
import plotly.figure_factory as ff

# 初始化Dash应用
app = JupyterDash(__name__)

df = [dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Complete=10),
      dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15', Complete=60),
      dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30', Complete=95)]

fig = ff.create_gantt(df, colors='Blues', index_col='Complete',
               show_colorbar=True, bar_width=0.5,
               showgrid_x=True, showgrid_y=True)

# 内嵌方式运行应用
app.layout = fig.show()
app.run_server(mode='inline')

方案3:改用Plotly Express生成甘特图(长期推荐)

figure_factory属于Plotly旧模块,官方更推荐使用plotly.express.timeline,兼容性更好且API更稳定:

import plotly.express as px
import pandas as pd

# 转换数据为DataFrame格式
df = pd.DataFrame([
    dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Complete=10),
    dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15', Complete=60),
    dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30', Complete=95)
])

# 生成甘特图
fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task", color="Complete",
                  color_continuous_scale='Blues')
fig.update_layout(showgrid_x=True, showgrid_y=True)
fig.show()

额外注意事项

  • M1 Mac环境下,确保Python环境为原生ARM架构(比如通过Miniforge安装),避免x86架构的兼容性问题
  • 升级Plotly到最新稳定版:pip install --upgrade plotly

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 15:12:44