使用 Matplotlib 创建动画直方图

PythonPythonBeginner
立即练习

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

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

简介

在本实验中,你将学习如何使用 Python 中的 Matplotlib 创建一个动画直方图。该动画直方图将模拟新数据的传入,并使用新数据更新矩形的高度。

虚拟机使用提示

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

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

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

导入库

首先,我们需要导入必要的库。

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation

设置随机种子和 bins

设置随机种子以确保可重复性,并确定 bins 的边界。

## Fixing random state for reproducibility
np.random.seed(19680801)

## Fixing bin edges
HIST_BINS = np.linspace(-4, 4, 100)

创建数据和直方图

使用 NumPy 创建数据和直方图。

## histogram our data with numpy
data = np.random.randn(1000)
n, _, _ = plt.hist(data, HIST_BINS, lw=1, ec="yellow", fc="green", alpha=0.5)

创建动画函数

我们需要创建一个 animate 函数,该函数生成新的随机数据并更新矩形的高度。

def animate(frame_number):
    ## simulate new data coming in
    data = np.random.randn(1000)
    n, _ = np.histogram(data, HIST_BINS)
    for count, rect in zip(n, bar_container.patches):
        rect.set_height(count)
    return bar_container.patches

创建条形图容器和动画

使用 plt.hist 可以让我们获得一个 BarContainer 实例,它是 Rectangle 实例的集合。我们使用 FuncAnimation 来设置动画。

## Using plt.hist allows us to get an instance of BarContainer, which is a
## collection of Rectangle instances. Calling prepare_animation will define
## animate function working with supplied BarContainer, all this is used to setup FuncAnimation.
fig, ax = plt.subplots()
_, _, bar_container = ax.hist(data, HIST_BINS, lw=1, ec="yellow", fc="green", alpha=0.5)
ax.set_ylim(top=55)  ## set safe limit to ensure that all data is visible.

ani = animation.FuncAnimation(fig, animate, 50, repeat=False, blit=True)
plt.show()

总结

在本实验中,你学习了如何使用 Python 中的 Matplotlib 创建动画直方图。你首先导入了必要的库,设置了随机种子和 bins,创建了数据和直方图,创建了一个动画函数,最后创建了条形图容器和动画。通过遵循这些步骤,你可以创建动画直方图以动态方式可视化数据。