动画直方图#

使用直方图BarContainer为动画直方图绘制一堆矩形。

import numpy as np

import matplotlib.pyplot as plt
import matplotlib.animation as animation

# Fixing random state for reproducibility
np.random.seed(19680801)
# Fixing bin edges
HIST_BINS = np.linspace(-4, 4, 100)

# histogram our data with numpy
data = np.random.randn(1000)
n, _ = np.histogram(data, HIST_BINS)

为了使直方图动画化,我们需要一个animate函数,它生成一组随机数字并更新矩形的高度。我们使用 python 闭包来跟踪我们将更新BarContainerRectangle 补丁的实例。

def prepare_animation(bar_container):

    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
    return animate

Usinghist()允许我们获取 的实例 BarContainer,它是实例的集合Rectangle。调用 prepare_animation将定义animate与提供的函数一起使用的函数 BarContainer,所有这些都用于设置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, prepare_animation(bar_container), 50,
                              repeat=False, blit=True)
plt.show()

脚本总运行时间:(0分7.371秒)

由 Sphinx-Gallery 生成的画廊