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

Jupyter Notebook导出HTML后含ipywidgets的交互式PCA图无法显示

问题根因

ipywidgets 的交互逻辑依赖Jupyter Notebook的Python运行时环境,默认导出HTML时仅会导出静态渲染结果,不会嵌入Python执行环境,也不会自动将widget的交互逻辑转换为前端可直接运行的JS代码,因此导出后下拉切换功能失效,图形无法正常显示。
你移除widget直接输出Plotly图时可以正常显示,是因为Plotly本身的交互逻辑完全基于JS实现,导出时会自动把对应JS逻辑嵌入HTML,不需要后端支持。

推荐解决方案

方案1:用Plotly原生下拉菜单替换ipywidgets(最优)

完全基于前端JS实现交互,导出HTML后可直接正常使用,兼容性最好,适配你需求的代码如下:

import plotly.express as px
import plotly.graph_objects as go

# 提取所有数值列作为可选维度
cols = components_df.select_dtypes('number').columns.tolist()

# 初始化默认显示前两个维度的散点图
fig = px.scatter(components_df, x=cols[0], y=cols[1],
                 color=dataTable_1['Class'], width=1000, height=700,
                 template='presentation',
                 labels=labels,
                 hover_data=['idx', 'SampleID'])

# 生成X轴切换下拉选项
x_buttons = []
for col in cols:
    x_buttons.append(dict(
        label=col,
        method='update',
        args=[
            {'x': [components_df[col]]},
            {'xaxis': {'title': col}},
            {'title': f"PCA Score Plot ({col} vs. {fig.layout.yaxis.title.text})"}
        ]
    ))

# 生成Y轴切换下拉选项
y_buttons = []
for col in cols:
    y_buttons.append(dict(
        label=col,
        method='update',
        args=[
            {'y': [components_df[col]]},
            {'yaxis': {'title': col}},
            {'title': f"PCA Score Plot ({fig.layout.xaxis.title.text} vs. {col})"}
        ]
    ))

# 挂载下拉菜单到画布
fig.update_layout(
    updatemenus=[
        dict(
            buttons=x_buttons,
            direction="down",
            showactive=True,
            x=0.1,
            xanchor="left",
            y=1.15,
            yanchor="top",
            pad={"r": 10, "t": 10},
            name="X轴维度"
        ),
        dict(
            buttons=y_buttons,
            direction="down",
            showactive=True,
            x=0.3,
            xanchor="left",
            y=1.15,
            yanchor="top",
            pad={"r": 10, "t": 10},
            name="Y轴维度"
        )
    ]
)

fig.show(config=config)

方案2:保留ipywidgets,导出时添加嵌入参数

如果一定要使用ipywidgets实现交互,可以通过nbconvert命令带参数导出,命令如下:

jupyter nbconvert --to html --embed-widgets 你的笔记本文件名.ipynb

该参数会将widget的相关JS依赖全部嵌入HTML文件,弊端是生成的文件体积会大幅增加,部分复杂交互可能存在兼容问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:24:06