Matplotlib を使ったアニメーション付きヒストグラム

PythonPythonBeginner
今すぐ練習

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

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、Python の Matplotlib を使ってアニメーション付きのヒストグラムを作成する方法を学びます。アニメーション付きのヒストグラムは、新しいデータが入力されるのをシミュレートし、新しいデータで長方形の高さを更新します。

VM のヒント

VM の起動が完了したら、左上隅をクリックして ノートブック タブに切り替え、Jupyter Notebook を使って練習します。

時々、Jupyter Notebook が読み込み完了するまで数秒待つ必要がある場合があります。Jupyter Notebook の制限により、操作の検証を自動化することはできません。

学習中に問題に遭遇した場合は、Labby にお問い合わせください。セッション後にフィードバックを提供してください。すぐに問題を解決いたします。

ライブラリのインポート

まず、必要なライブラリをインポートする必要があります。

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

乱数シードとビンの設定

再現性のために乱数シードを設定し、ビンの端を固定します。

## 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 を使用することで、Rectangle インスタンスのコレクションである BarContainer のインスタンスを取得できます。アニメーションを設定するために 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 を使ってアニメーション付きのヒストグラムを作成する方法を学びました。まず必要なライブラリをインポートし、乱数シードとビンを設定し、データとヒストグラムを作成し、アニメーション関数を作成し、最後にバーコンテナとアニメーションを作成しました。これらの手順に従うことで、動的にデータを可視化するためのアニメーション付きのヒストグラムを作成できます。