Matplotlib 图形和坐标轴的进入/离开事件

Beginner

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

简介

Matplotlib 是一个用于 Python 的数据可视化库。它提供了各种工具,可在 Python 中创建静态、动画和交互式可视化。Matplotlib 的交互式功能之一是能够检测鼠标何时进入和离开图形或坐标轴。在本实验中,我们将学习如何使用 Matplotlib 的图形和坐标轴进入/离开事件来更改图形和坐标轴的边框颜色。

虚拟机使用提示

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

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

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

导入 Matplotlib

在开始使用 Matplotlib 之前,我们需要导入它。我们还将导入 pyplot 模块,该模块为创建图表提供了一个简单的接口。

import matplotlib.pyplot as plt

创建图形和坐标轴

我们将使用 subplots 函数创建一个包含两个子图(坐标轴)的图形。我们还将设置图形的标题。

fig, axs = plt.subplots(2, 1)
fig.suptitle('Mouse Hover Over Figure or Axes to Trigger Events')

定义事件处理程序

我们现在将定义四个事件处理函数:on_enter_axeson_leave_axeson_enter_figureon_leave_figure。当鼠标进入或离开坐标轴或图形时,这些函数将会被调用。

def on_enter_axes(event):
    print('enter_axes', event.inaxes)
    event.inaxes.patch.set_facecolor('yellow')
    event.canvas.draw()

def on_leave_axes(event):
    print('leave_axes', event.inaxes)
    event.inaxes.patch.set_facecolor('white')
    event.canvas.draw()

def on_enter_figure(event):
    print('enter_figure', event.canvas.figure)
    event.canvas.figure.patch.set_facecolor('red')
    event.canvas.draw()

def on_leave_figure(event):
    print('leave_figure', event.canvas.figure)
    event.canvas.figure.patch.set_facecolor('grey')
    event.canvas.draw()

将事件处理程序连接到图形画布

现在,我们将使用 mpl_connect 方法将事件处理程序连接到图形画布。这样,当鼠标进入或离开图形或坐标轴时,事件处理程序就会被触发。

fig.canvas.mpl_connect('figure_enter_event', on_enter_figure)
fig.canvas.mpl_connect('figure_leave_event', on_leave_figure)
fig.canvas.mpl_connect('axes_enter_event', on_enter_axes)
fig.canvas.mpl_connect('axes_leave_event', on_leave_axes)

显示图形

现在我们将使用 show 函数来显示图形。

plt.show()

总结

在本实验中,我们学习了如何使用 Matplotlib 的图形和坐标轴进入/离开事件来更改图形和坐标轴的边框颜色。我们创建了一个包含两个子图的图形,定义了进入和离开图形及坐标轴的事件处理函数,将事件处理程序连接到图形画布,并显示了图形。