Google Colab上でmatplotlibのアニメーションを実行する場合、Jupyter notebookの方法と少し異なる。
matplotlibを用いたアニメーション作成方法自体は
matplotlib でアニメーションを作る - Qiita
などでで解説されているが。今回はGoogle Colab上でArtistAnimationとFuncAnimationを使った例について取り上げる。
以下のようにJupyter notebookではmatplotlib.animationをインポートした上でJupyter上でインタラクティブな画像表示するために%matplotlib nbagg
とすることで動画を表示することができる。
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation %matplotlib nbagg
Google Colab上ではnbagg機能が使用できないため、代わりにjavascriptを動かすコードを追記する必要がある。
以下ArtistAnimation
を使って乱数生成をアニメーションで表示するためのコードを示す。
import numpy as np import matplotlib.pyplot as plt from matplotlib import animation, rc from IPython.display import HTML fig = plt.figure() ims = [] for i in range(10): rand = np.random.randn(100) im = plt.plot(rand,'b') ims.append(im) anim = animation.ArtistAnimation(fig, ims,interval=100) rc('animation', html='jshtml') anim
from IPython.display import HTML
はJupyter上でhtmlを表示するために必要、rcはplotの書式を設定する関数: matplotlib.pyplot.rc — Matplotlib 3.5.1 documentationでhtmlをjshtml
とすることでjavascriptを動かすことができる。
これを実行するとスライダー付きのグラフが表示され再生ボタンをクリックすると、アニメーションが表示される。
ユーザ定義した描画関数を呼び出すFuncAnimation
を使用する場合は、事前にオブジェクトの生成や軸の設定を行ったうえでFuncAnimation
を用いてanim
生成し実行する。
size = 100 x = np.arange(size) fig, ax = plt.subplots() plt.close() ax.set_xlim(( 0, size)) ax.set_ylim((-3, 3)) line, = ax.plot([],[],'b') def animate(i): yrand=np.random.randn(size) line.set_data(x,yrand) return (line) anim = animation.FuncAnimation(fig, animate, frames=10, interval=100) rc('animation', html='jshtml') anim
ArtistAnimationの方が動画用のフレーム画像をfor文で生成して繋げるというわかりやすいスキームだが一度画像を生成する必要があり、FuncAnimationの方はframesの設定によって後から生成する画像数を指定することができる。