动画直方图#

使用直方图的 BarContainer 绘制一组矩形以创建动画直方图。

import functools

import matplotlib.pyplot as plt
import numpy as np

import matplotlib.animation as animation

# Setting up a random number generator with a fixed state for reproducibility.
rng = np.random.default_rng(seed=19680801)
# Fixing bin edges.
HIST_BINS = np.linspace(-4, 4, 100)

# Histogram our data with numpy.
data = rng.standard_normal(1000)
n, _ = np.histogram(data, HIST_BINS)

要使直方图动画化,我们需要一个 animate 函数,它生成一组随机数并更新矩形的高度。 animate 函数更新 RectangleBarContainer 实例上的补丁。

def animate(frame_number, bar_container):
    # Simulate new data coming in.
    data = rng.standard_normal(1000)
    n, _ = np.histogram(data, HIST_BINS)
    for count, rect in zip(n, bar_container.patches):
        rect.set_height(count)

    return bar_container.patches

使用 hist() 允许我们获得 BarContainer 的实例,它是一个 Rectangle 实例的集合。由于 FuncAnimation 仅将帧号参数传递给动画函数,因此我们使用 functools.partial 来修复 bar_container 参数。

# Output generated via `matplotlib.animation.Animation.to_jshtml`.

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.

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

标签: 绘图类型: 直方图 动画

脚本的总运行时间: (0 分钟 7.856 秒)

由 Sphinx-Gallery 生成的画廊