matplotlib 曲线上点击鼠标显示自定义标注,再点击鼠标之前的标注消失
时间: 2023-08-26 08:03:34 浏览: 37
您可以使用 matplotlib 中的 `Annotation` 和 `EventHandlers` 模块来实现这个功能。以下是一个示例代码:
```python
import matplotlib.pyplot as plt
# 创建一个 figure 和一个子图
fig, ax = plt.subplots()
# 绘制一条简单的曲线
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
line, = ax.plot(x, y)
# 定义一个空的注释对象
annotation = ax.annotate("", xy=(0,0), xytext=(20,20), textcoords="offset points",
bbox=dict(boxstyle="round", fc="w"),
arrowprops=dict(arrowstyle="->"))
# 定义一个点击事件处理函数
def onclick(event):
# 如果鼠标在曲线上
if line.contains(event)[0]:
# 获取当前点击位置的 x 和 y 坐标
x, y = event.xdata, event.ydata
# 更新注释文本和位置
annotation.set_text("x={:.2f}, y={:.2f}".format(x, y))
annotation.xy = (x, y)
# 显示注释
annotation.set_visible(True)
fig.canvas.draw_idle()
# 如果鼠标不在曲线上
else:
# 隐藏注释
annotation.set_visible(False)
fig.canvas.draw_idle()
# 连接鼠标点击事件和处理函数
fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
```
在这个示例中,我们首先创建了一个简单的曲线图,并定义了一个空的 `Annotation` 对象。然后,我们创建了一个鼠标点击事件处理函数 `onclick`,该函数会根据点击位置的不同更新注释文本和位置,并在需要时显示或隐藏注释。最后,我们将鼠标点击事件和该处理函数连接起来,并显示图形。