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

VSCode Jupyter中Plotly v4的Scatter.on_selection()回调无法触发如何解决?

解决Plotly FigureWidget回调函数不执行的问题

问题场景

使用Python 3.10运行以下代码,为FigureWidget绑定了选择和点击的回调函数,但操作图形时cb函数完全没有执行:

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

def cb(*arg):
    print(arg)
    
fig = go.FigureWidget([list(px.scatter(df,'Z1','Z2', color='Metra').select_traces())[0]])

fig.data[0].on_selection(cb)
fig.data[0].on_click(cb)

assert isinstance(fig, plotly.graph_objs.FigureWidget)

fig.show()

已安装Jupyter Notebook Renderers,怀疑其覆盖了Plotly原生交互逻辑,相关依赖版本:

  • IPython: 8.5.0
  • ipykernel: 6.16.0
  • ipywidgets: 8.0.2
  • jupyter_client: 7.4.2
  • jupyter_core: 4.11.1
  • nbclient: 0.7.0
  • nbconvert: 7.2.3
  • nbformat: 5.7.0
  • traitlets: 5.4.0

解决方案

1. 强制使用Plotly Widget渲染器

Jupyter Notebook Renderers会替换原生的Widget渲染逻辑,导致回调失效。在代码开头添加配置,强制使用widget渲染:

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

2. 改用Widget原生显示方式

不要调用fig.show(),直接将fig作为单元格最后一行输出,让Notebook自动渲染交互组件:

# 替换原有的fig.show()
fig

3. 修复ipywidgets扩展

确保ipywidgets的Notebook扩展已正确激活,执行以下命令:

jupyter nbextension enable --py widgetsnbextension

4. 调整依赖版本兼容

ipywidgets 8.x与Plotly FigureWidget存在部分兼容性问题,可尝试降级ipywidgets到7.x版本:

pip install ipywidgets==7.7.1

同时确保Plotly版本为5.x及以上:

pip install --upgrade plotly

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 09:30:37