注意
前往末尾以下载完整示例代码。
鼠标移动和点击事件#
一个示例,展示如何通过连接鼠标移动和点击事件与绘图画布进行交互。
注意
此示例展示了 Matplotlib 的交互功能,它不会出现在静态文档中。请在您的机器上运行此代码以查看交互性。
您可以复制粘贴部分内容,或使用页面底部的链接下载整个示例。

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backend_bases import MouseButton
t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)
def on_move(event):
if event.inaxes:
print(f'data coords {event.xdata} {event.ydata},',
f'pixel coords {event.x} {event.y}')
def on_click(event):
if event.button is MouseButton.LEFT:
print('disconnecting callback')
plt.disconnect(binding_id)
binding_id = plt.connect('motion_notify_event', on_move)
plt.connect('button_press_event', on_click)
plt.show()