動畫直方圖#

使用直方圖的 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 函式會更新 Rectangle,這是 BarContainer 實例上的貼片。

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 分鐘 13.650 秒)

由 Sphinx-Gallery 產生的圖庫