今日は、Pythonプログラミング言語を使って、アニメーションのヒストグラムを得るためのプログラミングをします。
Pythonとmatplotlibは、静的な2Dプロットを作成するために使用することができます。
しかし、matplotlib は動的な自動更新のアニメーションプロットを作成するのにも使える秘密の力を持っています。
さあ、はじめましょう
1. モジュールのインポート
まず最初に、データを作成するための numpy やヒストグラムをプロットするための matplotlib 、最後にアニメーションプロットを行うための matplotlib.animation など、必要なモジュールやライブラリーをインポートすることから始めました。
また、動画を HTML 形式に変換するために、HTML 関数もインポートする予定です。
|
1
2
3
4
5
|
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML
plt.style.use('seaborn')
|
2. データセットの作成
データを作成するために、まずランダムな状態を固定することでnumpyモジュールが必要になります。
次に、linespace関数を用いてビンの数を初期化します。
次に、linspace関数を使ってランダムな1000個のデータポイントを作成します。
|
1
2
3
4
|
np.random.seed(19680801)
HIST_BINS = np.linspace(-4, 4, 100)
data = np.random.randn(1000)
n, _ = np.histogram(data, HIST_BINS)
|
3. ヒストグラムをアニメーション化する
ヒストグラムをアニメーション化するためには,乱数を生成してビンの高さを更新し続ける関数 animate が必要です.
|
1
2
3
4
5
6
7
8
9
10
11
12
|
def prepare_animation(bar_container):
def animate(frame_number):
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
|
3. ヒストグラムのアニメーション表示
hist()関数を使って、BarContainer` ( Rectangle インスタンスのコレクション ) のインスタンスを取得することができます。
次に、prepare_animation を呼び出します。
この関数には animate という関数が定義されています。
最後に、to_html5_video 関数を使用して、プロットを HTML 形式に変換します。
|
1
2
3
4
5
|
fig, ax = plt.subplots()
_, _, bar_container = ax.hist(data, HIST_BINS, lw=1,ec="red", fc="blue", alpha=0.5)
ax.set_ylim(top=55)
ani = animation.FuncAnimation(fig, prepare_animation(bar_container), 50,repeat=True, blit=True)
HTML(ani.to_html5_video()) |
Python でアニメーションのヒストグラムを表示するための完全な実装
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML
plt.style.use('seaborn')
np.random.seed(19680804)
HIST_BINS = np.linspace(-4, 4, 100)
data = np.random.randn(1000)
n, _ = np.histogram(data, HIST_BINS)
def prepare_animation(bar_container):
def animate(frame_number):
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
fig, ax = plt.subplots()
_, _, bar_container = ax.hist(data, HIST_BINS, lw=1,ec="blue", fc="yellow", alpha=0.5)
ax.set_ylim(top=100)
ani = animation.FuncAnimation(fig, prepare_animation(bar_container), 50,repeat=True, blit=True)
HTML(ani.to_html5_video()) |
まとめ
ヒストグラムのアニメーションを楽しんでいただけましたでしょうか?データ、ビンの数、ヒストグラムの速度など、いろいろ試してみてください。
それでは、よいコーデを
Read More
- Python Plot:Pythonでアニメーションプロットを作成する
- matplotlibでプロットを効率的に行う3つのコツ
- Python 滑らかな曲線のプロット