matplotlib鼠标悬停显示标签横坐标的2倍
时间: 2023-11-07 08:07:39 浏览: 38
你可以使用 matplotlib 的事件处理程序来实现鼠标悬停显示标签横坐标的2倍。
以下是示例代码:
```python
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# 绘制折线图
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
line, = ax.plot(x, y)
# 创建标签
label = ax.annotate("", xy=(0,0), xytext=(20,20),
textcoords="offset points",
bbox=dict(boxstyle="round", fc="w"),
arrowprops=dict(arrowstyle="->"))
label.set_visible(False)
def hover(event):
# 鼠标悬停事件处理程序
if event.inaxes == ax:
x, y = event.xdata, event.ydata
label.set_text(f"x={x}, y={y*2}") # 将标签文本设置为横坐标的2倍
label.xy = (x,y)
label.set_visible(True)
fig.canvas.draw_idle()
else:
label.set_visible(False)
# 添加鼠标悬停事件处理程序
fig.canvas.mpl_connect("motion_notify_event", hover)
plt.show()
```
这段代码绘制了一个简单的折线图,并使用 `annotate` 函数创建了一个标签。在鼠标悬停时,将显示标签,并将标签文本设置为横坐标的2倍。注意,在 `hover` 函数中,需要调用 `fig.canvas.draw_idle()` 来更新图形。