pythonのグラフ描画用ライブラリである「matplotlib」でアニメーションを作成・保存する方法について紹介します。
本記事では、下記の内容を紹介します。
この記事で分かること
- matplotlibでアニメーションを作成
- matplotlibで複数のグラフのアニメーションを作成
- matplotlibで作成したアニメーションをgifで保存
- 【補足】FuncAnimationでアニメーションを作成
スポンサーリンク
matplotlibでアニメーションを作成する方法
はじめに、matplotlibで作成した1つのグラフをアニメーションにする方法について、紹介します。
matplotlibでアニメーションを作成する方法として、ArtistAnimationを用いる方法と、FuncAnimationを用いる方法の2通りの方法があります。
ArtistAnimationは、アニメーション化するグラフをあらかじめリストの形で用意しておき、それを順番に表示します。
FuncAnimationは、あらかじめグラフを用意するのではなく、アニメーションの1フレームごとに関数を実行し、関数の実行結果を順番に表示します。
とっつきやすいのはArtistAnimationの方ですが、あらかじめアニメーション化するグラフを作成しリストとして保持しないといけないため、重くなるという欠点があります。
本記事では、ArtistAnimation を用いたアニメーション作成方法を中心に紹介し、最後に補足的にFuncAnimationを用いた方法を紹介します。
matplotlibのArtistAnimationで、アニメーションを作成
はじめに、matplotlibのArtistAnimationで、アニメーションを作成する方法について紹介します。
matplotlib.animation.ArtistAnimation の引数の指定方法について、 公式ドキュメント から引用しました。
公式ドキュメント
figに、グラフ描画領域のfigオブジェクトを渡します。
artistsには、アニメーション化するグラフのリストを渡します。
以下、ArtistAnimationでアニメーションを作成するサンプルコードです。
### matplotlibでアニメーションを作成
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import ArtistAnimation
#グラフを表示する領域を,figオブジェクトとして作成.
fig = plt.figure(figsize = (5,5), facecolor='lightblue')
x = np.linspace(0, np.pi * 4, 100)
frames = []
for i in np.linspace(0, np.pi * 2, 30):
y = np.sin(x + i)
frame = plt.plot(x, y, color='blue')
frames.append(frame)
plt.legend(['sin'], loc='upper right')
ani = ArtistAnimation(fig, frames, interval=100)
plt.show()
コード実行後、表示されるアニメーションはこちらになります。
> %matplotlib notebook
筆者環境は jupyter notebook であるため、この一行を記述しています。
これを記述することで、matplotlibのグラフをインタラクティブモードで出力することができます。
とりあえず、jupyter notebookでアニメーションを表示する際に必要と覚えておいてください。
> x = np.linspace(0, np.pi * 4, 100)
0から4πまでの、2周期分の x の要素を作成しています。
> for i in np.linspace(0, np.pi * 2, 30):
0から2πまでの要素を30個作成し、順番に i に渡してループさせます。
> y = np.sin(x + i)
> frame = plt.plot(x, y, color='blue')
> frames.append(frame)
sinの値を更新しつつグラフを作成し、リストに追加しています。
> plt.legend(['sin'], loc='upper right')
凡例を表示しています。
凡例の表示方法については、下記の記事で詳しく紹介しています。
> ani = ArtistAnimation(fig, frames, interval=100)
ArtistAnimationで、アニメーションを作成しています。
intervalの単位はミリ秒です。
スポンサーリンク
matplotlibで複数のグラフのアニメーションを作成する方法
次に、matplotlibのArtistAnimationで複数のグラフのアニメーションを作成する方法を紹介します。
1つのfig領域の中に複数のグラフを作成するためには、複数のグラフそれぞれの領域をsubplotとして指定します。
複数のグラフを1つの領域の中に描画する方法については、下記の記事で紹介していますので基本が知りたい方は確認してみてください。
以下、複数のグラフのアニメーションを作成するサンプルコードです。
### matplotlibで複数のグラフのアニメーションを作成
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import ArtistAnimation
#グラフを表示する領域を,figオブジェクトとして作成.
fig = plt.figure(figsize = (5,5), facecolor='lightblue')
ax1 = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 2)
x = np.linspace(0, np.pi * 4, 100)
frames = []
for i in np.linspace(0, np.pi * 2, 30):
y1 = np.sin(x + i)
y2 = np.cos(x + i)
frame1 = ax1.plot(x, y1, color='blue')
frame2 = ax2.plot(x, y2, color='blue')
frames.append(frame1+frame2)
ax1.legend(['sin'], loc='upper right')
ax2.legend(['cos'], loc='upper right')
ani = ArtistAnimation(fig, frames, interval=100)
plt.show()
コード実行後、表示されるアニメーションはこちらになります。
> ax1 = fig.add_subplot(2, 1, 1)
> ax2 = fig.add_subplot(2, 1, 2)
figオブジェクトに、それぞれのグラフを描画するためのsubplotを追加しています。
引数には順番に、"行数"、”列数"、”位置”を指定します。
> frames.append(frame1+frame2)
2つのグラフをリストに追加しています。
スポンサーリンク
matplotlibで作成したアニメーションをgifで保存する方法
次に、matplotlibで作成したアニメーションをgifで保存する方法について紹介します。
アニメーションを保存するためには、ArtistAnimationのsaveメソッドを使用します。
以下、saveメソッドを用いて、アニメーションを保存するサンプルコードです。
### 作成したアニメーションをgifで保存
%matplotlib notebook
import matplotlib.pyplot as plt
from matplotlib.animation import ArtistAnimation
import numpy as np
import pathlib
#グラフを表示する領域を,figオブジェクトとして作成.
fig = plt.figure(figsize = (5,5), facecolor='lightblue')
x = np.linspace(0, np.pi * 4, 100)
frames = []
for i in np.linspace(0, np.pi * 2, 30):
y = np.sin(x + i)
frame = plt.plot(x, y, color='blue')
frames.append(frame)
plt.legend(['sin'], loc='upper right')
ani = ArtistAnimation(fig, frames, interval=100)
# pathlibモジュールでパスを作成する
path_dir = pathlib.Path(r'test')
path_gif = path_dir.joinpath('animation.gif')
ani.save(path_gif, writer='pillow')
plt.close()
> path_dir = pathlib.Path(r'test')
> path_gif = path_dir.joinpath('animation.gif')
pathlibモジュールで、pathオブジェクトを生成しています。
gifファイルのファイルパスは、joinpathで連結して作成しています。
pathlibモジュールの使用方法については、下記の記事で紹介しています。
> ani.save(path_gif, writer='pillow')
ArtistAnimationのsaveメソッドで、アニメーションを保存しています。
スポンサーリンク
【補足】matplotlibのFuncAnimationでアニメーションを作成する方法
補足として、FuncAnimationでアニメーションを作成する方法を紹介します。
matplotlib.animation.FuncAnimation の引数の指定方法について、 公式ドキュメント から引用しました。
公式ドキュメント
funcに、グラフを描画する関数を指定する必要があります。
以下、matplotlib.animation.FuncAnimationでアニメーションを作成するサンプルコードです。
### FuncAnimationでアニメーションを作成
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
def plot_hist(data):
plt.cla()
# 平均0、標準偏差10、の正規分布の乱数を1,000個生成
x = np.random.normal(0, 10, 1000)
frame = plt.hist(x, bins=20, range=(-50, 50), density=True, ec='black')
#グラフを表示する領域を,figオブジェクトとして作成.
fig = plt.figure(figsize = (5,5), facecolor='lightblue')
ani = FuncAnimation(fig, plot_hist, interval=100)
plt.show()
コード実行後、表示されるアニメーションはこちらになります。
> def plot_hist(data):
正規分布に従った乱数を生成し、ヒストグラムを描画する関数を定義しています。
> ani = FuncAnimation(fig, plot_hist, interval=100)
FuncAnimationの引数に、ヒストグラムを描画する関数である「plot_hist」を指定しています。
FuncAnimationで作成したアニメーションをgifで保存する方法
FuncAnimationで作成したアニメーションをgif形式で保存する方法を紹介します。
アニメーションを保存するためには、FuncAnimationのsaveメソッドを使用します。
以下、saveメソッドを用いて、アニメーションを保存するサンプルコードです。
### 作成したアニメーションをgifで保存
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
def plot_hist(data):
plt.cla()
# 平均0、標準偏差10、の正規分布の乱数を1,000個生成
x = np.random.normal(0, 10, 1000)
frame = plt.hist(x, bins=20, range=(-50, 50), density=True, ec='black')
#グラフを表示する領域を,figオブジェクトとして作成.
fig = plt.figure(figsize = (5,5), facecolor='lightblue')
ani = FuncAnimation(fig, plot_hist, interval=100, frames=10)
# pathlibモジュールでパスを作成する
path_dir = pathlib.Path(r'test')
path_gif = path_dir.joinpath('animation-hist.gif')
ani.save(path_gif, writer='pillow')
plt.close()
> ani = FuncAnimation(fig, plot_hist, interval=100, frames=10)
グラフの表示回数を決めないとgif形式で保存できないため、framesでグラフの枚数を指定しています。
> ani.save(path_gif, writer='pillow')
saveメソッドで、gif形式で保存しています。
スポンサーリンク