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

Jupyter Lab中Plotly Go Figure嵌入Widget后图表不显示的解决办法

解决Jupyter Lab中Plotly FigureWidget图表不显示的问题

问题背景

在Jupyter Lab中开发包含Plotly Graph Objects(go)的交互式Widget时,Widget控件能正常显示,但其中的Plotly图表无法渲染。参考官方示例添加display代码后问题依旧,相关代码如下。

解决方案

1. 确认Jupyter Lab扩展安装正确

Plotly FigureWidget需要对应Jupyter Lab扩展支持,激活你的Python环境后执行以下命令:

pip install plotly ipywidgets
jupyter labextension install @jupyter-widgets/jupyterlab-manager plotlywidget

安装完成后重启Jupyter Lab。

2. 修正滑块类型不匹配问题

原代码中month滑块参数使用浮点数(如value=1.0),但数据集df['month']为整数类型,导致初始过滤无数据,图表无法显示。需将滑块参数改为整数:

month = widgets.IntSlider(
    value=1,
    min=1,
    max=12,
    step=1,
    description='Month:',
    continuous_update=False
)

3. 修复response函数的硬编码错误

原代码中当use_date为False时,硬编码了航空公司为DL,导致切换航空公司控件时数据不更新,需改为使用textbox.value:

filter_list = [i and j for i, j in
               zip(df['carrier'] == textbox.value, df['origin'] == origin.value)]

修正后的完整代码

import numpy as np
import pandas as pd
from IPython.display import display

import plotly.graph_objects as go
from ipywidgets import widgets

df = pd.read_csv(
    'https://raw.githubusercontent.com/yankev/testing/master/datasets/nycflights.csv')
df = df.drop(df.columns[[0]], axis=1)

month = widgets.IntSlider(
    value=1,
    min=1,
    max=12,
    step=1,
    description='Month:',
    continuous_update=False
)

use_date = widgets.Checkbox(
    description='Date: ',
    value=True,
)

container = widgets.HBox(children=[use_date, month])

textbox = widgets.Dropdown(
    description='Airline:   ',
    value='DL',
    options=df['carrier'].unique().tolist()
)

origin = widgets.Dropdown(
    options=list(df['origin'].unique()),
    value='LGA',
    description='Origin Airport:',
)


# 初始化带双轨迹的FigureWidget
trace1 = go.Histogram(x=df['arr_delay'], opacity=0.75, name='Arrival Delays')
trace2 = go.Histogram(x=df['dep_delay'], opacity=0.75, name='Departure Delays')
g = go.FigureWidget(data=[trace1, trace2],
                    layout=go.Layout(
                        title=dict(
                            text='NYC FlightDatabase'
                        ),
                        barmode='overlay'
                    ))
def validate():
    if origin.value in df['origin'].unique() and textbox.value in df['carrier'].unique():
        return True
    else:
        return False


def response(change):
    if validate():
        if use_date.value:
            filter_list = [i and j and k for i, j, k in
                           zip(df['month'] == month.value, df['carrier'] == textbox.value,
                               df['origin'] == origin.value)]
            temp_df = df[filter_list]

        else:
            filter_list = [i and j for i, j in
                           zip(df['carrier'] == textbox.value, df['origin'] == origin.value)]
            temp_df = df[filter_list]
        x1 = temp_df['arr_delay']
        x2 = temp_df['dep_delay']
        with g.batch_update():
            g.data[0].x = x1
            g.data[1].x = x2
            g.layout.barmode = 'overlay'
            g.layout.xaxis.title = 'Delay in Minutes'
            g.layout.yaxis.title = 'Number of Delays'


origin.observe(response, names="value")
textbox.observe(response, names="value")
month.observe(response, names="value")
use_date.observe(response, names="value")

container2 = widgets.HBox([origin, textbox])
widg = widgets.VBox([container,
              container2,
              g])

display(widg)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 13:43:12