つれづれなる備忘録

日々の発見をあるがままに綴る

Google Colabでpython8 ~ アニメーションの実行

 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を動かすことができる。

これを実行するとスライダー付きのグラフが表示され再生ボタンをクリックすると、アニメーションが表示される。

"Google Colab上でアニメーション"
Google Colab上でアニメーション

ユーザ定義した描画関数を呼び出す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の設定によって後から生成する画像数を指定することができる。