备注
Go to the end 下载完整的示例代码..
动画直方图#
使用直方图的 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 函数更新 BarContainer 实例上的 Rectangle 补丁.
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 分 10.579 秒)