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

mplcursors实现同一绘图hover/点击双触发及散点差异化交互方法

解决mplcursors同时支持悬停+点击交互及不同散点自定义行为

一、同时实现鼠标悬停和点击触发注释

mplcursors允许创建多个独立的Cursor实例,分别绑定不同触发逻辑,就能在同一绘图中同时支持悬停和点击交互:

  • 第一个Cursor实例设置hover=True,处理悬停触发注释
  • 第二个Cursor实例设置multiple=True(支持多注释留存),并绑定add事件将注释设为可拖动,处理点击触发

示例代码:

import matplotlib.pyplot as plt
import mplcursors

x1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
x2 = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

fig, ax = plt.subplots()
ax.set_title("Hover + Click (draggable) Annotations")
scatter1 = ax.scatter(x1, x1, label="Series 1")
scatter2 = ax.scatter(x2, x2, label="Series 2")

# 悬停触发注释
hover_cursor = mplcursors.cursor(hover=True)
# 点击触发可拖动注释
click_cursor = mplcursors.cursor(multiple=True)
click_cursor.connect("add", lambda sel: sel.annotation.draggable(True))

plt.legend()
plt.show()

二、为同一绘图内不同散点设置不同交互行为

通过给mplcursors.cursor()指定target参数,可针对单个散点对象绑定独立Cursor实例,实现差异化交互:

  • 比如让scatter1仅响应悬停,scatter2仅响应点击且注释可拖动

示例代码:

import matplotlib.pyplot as plt
import mplcursors

x1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
x2 = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

fig, ax = plt.subplots()
ax.set_title("Different Interactions per Scatter Series")
scatter1 = ax.scatter(x1, x1, label="Hover Only")
scatter2 = ax.scatter(x2, x2, label="Click (Draggable) Only")

# 仅scatter1响应悬停
mplcursors.cursor(scatter1, hover=True)
# 仅scatter2响应点击,注释可拖动
click_cursor = mplcursors.cursor(scatter2, multiple=True)
click_cursor.connect("add", lambda sel: sel.annotation.draggable(True))

plt.legend()
plt.show()

关键说明

  • 每个Cursor实例独立管理触发方式和目标对象,互不干扰
  • 若需自定义注释内容,可在connect("add")的回调中通过sel.annotation.set_text()修改显示内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 23:20:13