matplotlibでアニメーション
matplotlibのアニメーション機能の備忘録です。
matplotlib のアニメーションは ArtistAnimation と FuncAnimation の2種類があ利ます。ArtistAnimation は、あらかじめ全てのグラフを配列の形で用意しておき、それを1枚ずつ表示するものです。FuncAnimation は予め完成したグラフを渡すのではなく、アニメーションの1フレームごとに関数を実行する。データが巨大すぎる場合や、アニメーションが無限に続く場合に利用します。
ArtistAnimation
全てのグラフを配列の形で用意し、それを1枚ずつ表示するイメージです。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
ims = []
for i in range(10):
j = np.arange(0, 2*np.pi*(i+1)/10, 0.01)
x = np.sin(3*j)
y = 2*np.sin(4*j)
im = plt.plot(x,y)
ims.append(im)
# 10枚のプロットを 300ms ごとに表示
ani = animation.ArtistAnimation(fig, ims, interval=300)
plt.show()
#ani.save("output01.gif", writer="imagemagick")
動画をGIFで保存する際は、末尾の
plt.show()
をコメントアウトして
ani.save("output.gif", writer="imagemagick")
に変更するとGIFファイルに保存出来ます。この時、imagemagick というパッケージが必要になります。インストールは
https://fukatsu.tech/install-imagemagick
を参考にしました。
FuncAnimation
こちらは予め完成したグラフを渡すのではなく、アニメーションの1フレームごとに関数を実行する。データが巨大すぎる場合やアニメーションが無限に続く場合に利用します。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
frame_no=0
def plot(data):
global frame_no
frame_no = frame_no + 1
plt.cla() # 現在描写されているグラフを消去
j = np.arange(0, 2*np.pi*frame_no/10, 0.01)
x = np.sin(j)
y = 2*np.sin(2*j)
im = plt.plot(x,y) # グラフを生成
ani = animation.FuncAnimation(fig, plot, interval=300,frames=30)
#ani.save("/Users/tanabemasayuki/Desktop/いろいろ/output02.gif", writer="imagemagick")
plt.show()
こちらは動的にグラフを作るため、定義域と値域が関数の値によって変化します。
GIFに出力する場合、ArtistAnimation と違って終わりが指定されていないので、
ani = animation.FuncAnimation(fig, plot, interval=300,frames=30)
ani.save("output02.gif", writer="imagemagick")
という具合に frames=30 とフレーム数を指定します。

チョットおしゃれなリサージュ図形
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
frame_no=0
def plot(data):
global frame_no
frame_no = frame_no + 1
plt.cla() # 現在描写されているグラフを消去
j = np.arange(0, 2*np.pi*frame_no/20, 0.01)
x = np.sin(5*j)
y = 2*np.sin(6*j)
im = plt.plot(x,y) # グラフを生成
ani = animation.FuncAnimation(fig, plot, interval=300,frames=30)
#ani.save("/Users/tanabemasayuki/Desktop/いろいろ/output03.gif", writer="imagemagick")
plt.show()




