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

如何在Panel的Row组件中保留matplotlib可点击绘图的交互功能

你遇到的交互失效问题是因为直接将matplotlib原生figure传入Panel组件时,默认采用静态渲染逻辑,不会保留matplotlib的事件回调机制,需要按以下方式调整:

完整修改后可运行代码

import matplotlib.pyplot as plt
import panel as pn

# 加载Panel的matplotlib适配扩展,必须放在初始化阶段
pn.extension("matplotlib")

class custom_objects_to_plot:
    def __init__(self, x, y, name):
        self.x = x
        self.y = y
        self.name = name

a = custom_objects_to_plot(10, 20, "a")
b = custom_objects_to_plot(30, 5, "b")
c = custom_objects_to_plot(40, 30, "c")
d = custom_objects_to_plot(120, 10, "d")

# 提前初始化布局,方便回调中更新
my_row = pn.Row()

def on_pick(event):
    # 可直接获取点击点绑定的元数据:event.artist.obj
    my_fig, my_ax = plt.subplots()
    my_ax.scatter([1, 2, 3, 4], [5, 6, 7, 8])
    # 新图也封装为Panel的Matplotlib交互面板
    new_plot = pn.pane.Matplotlib(my_fig, interactive=True, width=400)
    # 加入现有布局即可渲染,如需弹窗效果可替换为Panel的Modal组件实现
    my_row.append(new_plot)

fig, ax = plt.subplots()
for obj in [a, b, c, d]:
    artist = ax.plot(obj.x, obj.y, 'ro', picker=5)[0]
    artist.obj = obj

# 用Matplotlib面板包裹原图,显式开启交互模式
mpl_pane = pn.pane.Matplotlib(fig, interactive=True, width=400)
# 将回调绑定到Panel提供的交互画布上,而非原生figure的canvas
mpl_pane.canvas.callbacks.connect('pick_event', on_pick)

my_row.append(mpl_pane)
my_row.show()

关键修改说明

  • 必须先调用pn.extension("matplotlib")加载适配扩展,否则web端的交互逻辑无法正常生效
  • 所有matplotlib图表都需要用pn.pane.Matplotlib封装,且显式指定interactive=True开启交互能力,不能直接传入原生figure对象
  • 事件回调需要绑定到封装后的mpl_pane.canvas,Panel会基于这个封装后的画布处理web端的交互事件
  • 回调中不要使用原生plt.show(),web环境下该方法无效,新生成的图表同样封装为Matplotlib面板后加入Panel布局即可渲染

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 20:54:01