プログラミング
記事内に商品プロモーションを含む場合があります

Matplitlib|Google Colab上でグラフをアニメーションさせる方法

tadanori

matplitlib.animationを使うと、グラフをアニメーションさせることができますが、Google Colab上ではそのままではアニメーションできません。ここでは、Google Colab上でグラフをアニメーションさせる方法について解説します。

方法(結論)

Jupyter notebookの場合、matplotlib.animationをインポートした後に以下のマジックコマンドを追加することでアニメーションを追加することが可能です。

%matplotlib nbagg

ただ、Google Colabではnbaggを設定しただけではアニメーションできません。

これに加えて以下のコードでjavascriptでアニメーションさせるように設定する必要があります

from matplotlib import animation, rc

rc('animation', html='jshtml')

上記の2つをおまじないと思って記述しておけばOKです

結論

Google Colabでアニメーションさせたい場合は、以下のコードを最初にいれておけばOK

from matplotlib import animation, rc

%matplotlib nbagg
rc('animation', html='jshtml')

アニメーション例

アニメーション例①:animation.ArtistAnimation

最初にplt.plotで複数のグラフを作成しておき、これをアニメーションされる例です。

animation.ArtistAnimationを利用してアニメーションを生成させます。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation, rc
%matplotlib nbagg
rc('animation', html='jshtml')

fig = plt.figure()
ims = []
rand = np.random.randn(1000)
for i in range(10):
  im = plt.plot(rand[i*10:900+i*10],'b')
  ims.append(im)

ani = animation.ArtistAnimation(fig, ims,interval=100)

ani

表示は以下のようになります。

画面の例

アニメーションは以下のようになります

アニメーション

また、アニメーションは、以下のコードでgifファイルとして保存できます

ani.save("xxx.gif")

アニメーション例②:animation.FuncAnimation

動的にデータを生成する例です。

表示するデータを作成する関数(例ではplot())を作成しておき、呼び出します。

動的に生成する場合はanimation.FuncAnimationを利用してアニメーションを生成します。

Colabで表示させるには、何フレーム(何枚)の画像を生成させるかを指定する引数framesを指定する必要があります

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation, rc
%matplotlib nbagg
rc('animation', html='jshtml')

v = np.random.randn(200)

def plot(data):
    plt.cla()
    plt.plot(v[data: data+100])
    plt.tick_params(
      axis='x',            
      which='both',       
      bottom=True,      
      top=False,          
      labelbottom=False) 

fig = plt.figure()
ani = animation.FuncAnimation(fig, plot, interval=10, frames=100)

ani
アニメーション例2

まとめ

Google Colabでアニメーションを表示させようとしてハマりましたので記事にしました。

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

記事URLをコピーしました