如何让你的 Artist 支持 pick_event?
解读
在国内一线互联网与量化公司面试中,pick_event 是区分“只会调 plt.plot”与“能二次开发 Matplotlib”的试金石。
面试官真正想确认的是:
- 你是否理解 Matplotlib 事件循环与 Artist 树的耦合方式;
- 能否在不改源码的前提下,让自定义 Artist(如继承自
matplotlib.artist.Artist的组件)像Line2D、Patch一样响应鼠标; - 是否知道 contains() 与 picker 两套接口的差异与性能权衡;
- 能否把事件坐标映射到数据坐标,并给出 O(1) 或 O(log n) 的命中策略,避免在 10 万点场景下把主线程卡死。
一句话:让 Artist 具备“可被鼠标选中”的能力,同时保证 跨后端一致性 与 Jupyter 交互零延迟。
知识点
- Artist.contains(event)
返回 (bool, dict),决定当前 Artist 是否被命中;dict 可携带附加信息供回调使用。 - Artist.set_picker(picker)
picker 可以是 bool、float(半径阈值)、callable;Matplotlib 在FigureCanvasBase.pick()里会遍历可见、可拾取 Artist 并调用 contains。 - canvas.mpl_connect('pick_event', handler)
事件对象携带mouseevent、artist、ind等字段;handler 内禁止重量级计算,否则阻塞 GUI 主循环。 - 坐标系转换链
event.x, event.y→display→axes.transData.inverted()→data坐标;自定义 Artist 必须实现 get_transform() 并保证与 contains 内使用同一变换,否则出现“点不准”问题。 - 后端差异
TkAgg 在 Windows 下用 Win32 消息,Qt5Agg 用信号槽,WebAgg 用 WebSocket;contains 里若用 NumPy Mask 必须保证线程安全,禁止直接改 GUI 对象。 - 性能陷阱
对散点图级别 ≥1e5 时,暴力距离计算会触发 GIL;正确姿势是 空间索引(KD-Tree)+ 异步回调,或提前生成 Path 对象 用contains_point的 C++ Agg 路径检测。 - 测试覆盖
Matplotlib 官方 2000+ 单元测试里,test_picker.py用 FakeMouseEvent 模拟命中;国内面试常追问“如何写单测”,答案需给出pytest-mpl+matplotlib.testing.decorators.cleanup模板。
答案
分四步落地,代码可直接在白板手写:
import matplotlib.pyplot as plt
from matplotlib.artist import Artist
import numpy as np
class MyScatter(Artist):
_picker_threshold = 5 # 像素半径
def __init__(self, ax, x, y, **kw):
super().__init__()
self.ax = ax
self.x = np.asarray(x, dtype=float)
self.y = np.asarray(y, dtype=float)
self.set_picker(True) # 关键:打开拾取开关
ax.add_artist(self) # 加入 Artist 树
def contains(self, mouseevent):
# 1. 事件坐标 → 数据坐标
x0, y0 = self.ax.transData.inverted().transform(
(mouseevent.x, mouseevent.y))
# 2. 计算屏幕距离(像素级)
xs, ys = self.ax.transData.transform(np.column_stack([self.x, self.y])).T
dx = xs - mouseevent.x
dy = ys - mouseevent.y
dist = np.hypot(dx, dy)
# 3. 命中判定
ind = np.nonzero(dist <= self._picker_threshold)[0]
if len(ind):
return True, {'ind': ind, 'dist': dist[ind]}
return False, {}
def draw(self, renderer):
# 最少实现:用 Agg 路径一次性渲染
from matplotlib.path import Path
from matplotlib.patches import PathPatch
path = Path(np.column_stack([self.x, self.y]))
patch = PathPatch(path, facecolor='none', edgecolor='C0')
patch.draw(renderer)
# 使用示例
fig, ax = plt.subplots()
x = np.random.rand(1000)
y = np.random.rand(1000)
artist = MyScatter(ax, x, y)
def on_pick(event):
if event.artist is artist:
ind = event.ind['ind']
print('命中点索引:', ind)
fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()
要点强调
- 必须重写 contains,否则默认返回 (False, {})。
- set_picker(True) 只是门票,真正逻辑在 contains。
- 命中字典里带
ind,与官方Line2D行为一致,方便上层封装。 - 若数据量巨大,把距离计算换成 scipy.spatial.cKDTree 并在
__init__预构建,contains 内只做query_ball_point,复杂度从 O(n) 降到 O(log n)。 - 如果自定义 Artist 内部还有子 Artist(如复合箭头),需要在 contains 里递归调用子对象并合并结果,保证 事件冒泡 语义正确。
拓展思考
- 多 Artist 协同拾取
当 Figure 里同时存在MyScatter、MyErrorbar、MyText时,如何控制优先级?
答:在Figure.pick()遍历顺序基础上,给每个 Artist 加zorder与pickradius权重;或在回调里手动event.artist.set_zorder(999)实现“置顶选中”。 - 3D Axes 的 pick_event
Axes3D的transData是proj3d.proj_transform组合,contains 里需把三维数据投影到二维再算距离;同时注意 深度缓存 可能导致视觉上“挡在后面”的点被先命中,需用 z-buffer 值二次过滤。 - Web 后端与 JupyterLab
WebAgg 的 pick 事件通过 ipympl 的 WebSocket 回传,若 contains 计算过重会阻塞 UI 线程;解决方法是把命中检测下沉到 TypeScript 层,或在前端用 WebGL 拾取缓冲区,实现 60 fps 交互。 - 单元测试模板
国内 CI 多用 GitLab-Runner + pytest-mpl;测试 pick 需构造matplotlib.backend_bases.MouseEvent,并用canvas.draw()强制刷新,最后断言回调被触发且ind正确。 - GPU 加速路线
对 1e6 级粒子渲染,可把坐标上传为 OpenGL SSBO,在 shader 里做半径剔除,回读命中索引;Matplotlib 的 mpl-gl 实验分支已提供gl_artist基类,只需实现gl_contains()即可对接原有事件系统。