使用 Matplotlib 绘图进行鼠标交互

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

本实验展示了一个示例,演示如何使用 Python 中的 Matplotlib 库连接到移动和点击事件,从而与绘图画布进行交互。Matplotlib 是一个数据可视化库,允许用户在 Python 中创建静态、动画和交互式可视化。

虚拟机提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们将立即为你解决问题。

创建正弦波图

首先,我们需要使用 numpy 和 matplotlib 库创建一个正弦波图。

import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)

鼠标移动事件

我们可以使用 motion_notify_event 方法连接到鼠标移动事件。在这个示例中,当鼠标在绘图区域上移动时,我们会打印出 x 和 y 数据坐标以及 x 和 y 像素坐标。

def on_move(event):
    if event.inaxes:
        print(f'data coords {event.xdata} {event.ydata},',
              f'pixel coords {event.x} {event.y}')

binding_id = plt.connect('motion_notify_event', on_move)

鼠标点击事件

我们可以使用 button_press_event 方法连接到鼠标点击事件。在这个示例中,当鼠标左键被点击时,我们会断开鼠标移动事件的回调。

from matplotlib.backend_bases import MouseButton

def on_click(event):
    if event.button is MouseButton.LEFT:
        print('disconnecting callback')
        plt.disconnect(binding_id)

plt.connect('button_press_event', on_click)

显示绘图

最后,我们需要使用 show 方法来显示绘图。

plt.show()

总结

本实验展示了如何使用鼠标移动和点击事件与 Matplotlib 绘图进行交互。通过连接到这些事件,我们可以执行各种操作,如打印鼠标指针的坐标、断开回调等。这种技术对于在 Python 中创建交互式可视化很有用。