【Python】matplotlibのGIFアニメーションを作成する

オブジェクト指向でのGIFアニメーション作成方法を記載する。

事前準備

matplotlibのオブジェクト指向とはplt.plotではなくax.plot()でプロットする方法のこと。
グラフの軸やプロットラインがアーティストと呼ばれることを知っていると理解が楽。
オブジェクト指向やアーティストの説明は下記のブログなどを参照。
matplotlibをオブジェクト指向スタイルで使う その1 - minus9d's diary
matplotlib - matplotlib の使うために理解するべき基本要素 - Pynote

またgifアニメーションの作成には事前準備が必要。
下記のブログなどを参照。
matplotlibでアニメーションを作成,保存 - 粗大メモ置き場


GIFアニメの保存

import matplotlib.pyplot as plt
import matplotlib.animation as animation
#グラフ作成
fig, ax = plt.subplots(1,1)
a1 = ax.plot([0, 0])
a2 = ax.plot([1, 1])
a3 = ax.plot([2, 2])
#リストのリストとしてartistを保存
arts = [a1, a2, a3]
#アニメの作成
ani = animation.ArtistAnimation(fig, arts)
#gifファイルとして保存
ani.save('axes.gif', writer='imagemagick')

f:id:gushigo:20190505224934g:plain

理解を深めるために

アニメーションの原理とmatplotlibの構造を理解するために下記のコードでGIFを作成する。

import matplotlib.pyplot as plt
import matplotlib.animation as animation
#グラフ作成
fig, ax = plt.subplots(1,1)
ax.plot([0, 0])
ax.plot([1, 1])
ax.plot([2, 2])
#画像の保存
fig.savefig('image.png')
#リストのリストとしてartistを取得
arts = [[art] for art in ax.get_children()]
#アニメの作成
ani = animation.ArtistAnimation(fig, arts)
#gifファイルとして保存
ani.save('alL_arts.gif', writer='imagemagick')

#artsの中身の確認
print(arts)
# Out:
#[[<matplotlib.lines.Line2D at 0xb80dc97a20>],
# [<matplotlib.lines.Line2D at 0xb80c8cc080>],
# [<matplotlib.lines.Line2D at 0xb80c8cc208>],
# [<matplotlib.spines.Spine at 0xb80dc93630>],
# [<matplotlib.spines.Spine at 0xb80dc93748>],
# [<matplotlib.spines.Spine at 0xb80dc93860>],
# [<matplotlib.spines.Spine at 0xb80dc93978>],
# [<matplotlib.axis.XAxis at 0xb80dc93a58>],
# [<matplotlib.axis.YAxis at 0xb80dcaf0f0>],
# [Text(0.5,1,'')],
# [Text(0,1,'')],
# [Text(1,1,'')],
# [<matplotlib.patches.Rectangle at 0xb80c8b5828>]]

image.png
f:id:gushigo:20190505225521p:plain
alL_arts.gif
f:id:gushigo:20190505223319g:plain

ArtistAnimationでは第一引数にfigureを、第二引数にリスト与えている。
リストはfigureが持つアーティストでないといけないはず。
アニメーションはリストに含まれないアーティストがすべて表示された状態で、リストのアーティストが一つずつ表示されるようになっているように思える。

ちなみにSpyderにてウィンドウでグラフ表示しているときにani.save()をすると、ウィンドウにはアニメーションが表示されたが、ファイルとして保存されなかった。ウィンドウを消してから同じコマンドを実行したら無事保存された。謎挙動。