使用 Python Matplotlib 进行交互式数据可视化

PythonPythonBeginner
立即练习

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

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

简介

本实验将引导你了解如何在多个画布间交互数据。通过在一个轴上选择并突出显示一个点,你将生成该点在另一个轴上的数据。本实验我们将使用 Python Matplotlib。

虚拟机使用提示

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

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

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

导入库

我们将首先导入必要的库。

import numpy as np
import matplotlib.pyplot as plt

生成数据

我们将使用 NumPy 生成随机数据。

np.random.seed(19680801)
X = np.random.rand(100, 200)
xs = np.mean(X, axis=1)
ys = np.std(X, axis=1)

创建图形和轴

我们将创建一个带有两个轴的图形。

fig, (ax, ax2) = plt.subplots(2, 1)

绘制数据

我们将在第一个轴上绘制生成的数据。

line, = ax.plot(xs, ys, 'o', picker=True, pickradius=5)

创建点浏览器类

我们将创建一个类来处理点浏览器的功能。

class PointBrowser:
    def __init__(self):
        self.lastind = 0

        self.text = ax.text(0.05, 0.95, 'selected: none',
                            transform=ax.transAxes, va='top')
        self.selected, = ax.plot([xs[0]], [ys[0]], 'o', ms=12, alpha=0.4,
                                 color='yellow', visible=False)

    def on_press(self, event):
        if self.lastind is None:
            return
        if event.key not in ('n', 'p'):
            return
        if event.key == 'n':
            inc = 1
        else:
            inc = -1

        self.lastind += inc
        self.lastind = np.clip(self.lastind, 0, len(xs) - 1)
        self.update()

    def on_pick(self, event):

        if event.artist!= line:
            return True

        N = len(event.ind)
        if not N:
            return True

        ## the click locations
        x = event.mouseevent.xdata
        y = event.mouseevent.ydata

        distances = np.hypot(x - xs[event.ind], y - ys[event.ind])
        indmin = distances.argmin()
        dataind = event.ind[indmin]

        self.lastind = dataind
        self.update()

    def update(self):
        if self.lastind is None:
            return

        dataind = self.lastind

        ax2.clear()
        ax2.plot(X[dataind])

        ax2.text(0.05, 0.9, f'mu={xs[dataind]:1.3f}\nsigma={ys[dataind]:1.3f}',
                 transform=ax2.transAxes, va='top')
        ax2.set_ylim(-0.5, 1.5)
        self.selected.set_visible(True)
        self.selected.set_data(xs[dataind], ys[dataind])

        self.text.set_text('selected: %d' % dataind)
        fig.canvas.draw()

连接事件处理程序

我们将把事件处理程序连接到图形画布上。

browser = PointBrowser()

fig.canvas.mpl_connect('pick_event', browser.on_pick)
fig.canvas.mpl_connect('key_press_event', browser.on_press)

显示绘图

我们将显示该绘图。

plt.show()

总结

在本实验中,我们学习了如何使用 Python 的 Matplotlib 与多个画布进行数据交互。我们创建了一个类来处理点浏览器功能,并将事件处理程序连接到图形画布以实现交互性。