matplotlib 動画・アニメーション作成 †主な手法は2つらしい. 個人的には画像で掃き出して動画は ffmpeg コマンドにしているが,ここではあえて Python で動画を作成する. import matplotlib.pyplot as plt import matplotlib.animation as animation animation.FuncAnimation †ArtistAnimationは タイトルを動的に設定できない?ため,FuncAnimation を使いたい. def update_pcolor(istep, ax, X, Y, pcdata, time_in_datetime):
PC = ax.pcolor(X, Y, pcdata[istep,:,:])
PC.set_clim([0.,1.])
ax.set_title(time_in_datetime[istep].strftime('%Y/%m/%d')) # formatは例
def main():
fig = plt.figure()
ax = fig.add_subplot(111)
# とりあえず1回書いとく
PC = ax.pcolor(lon, lat, pcdata[0,:,:])
ax.axis('scaled')
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
cbar = fig.colorbar(PC)
cbar.ax.set_ylabel('colorbar label [unit]')
ax.set_yticks(yticks)
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ani = animation.FuncAnimation(fig, update_pcolor, fargs=(ax, X, Y, pcdata, time_in_datetime), intetrval=num, frames=N)
ani.save('filename.gif',writer='XXX')
update_pcolor に xlabel 等を入れると毎回描くことになり時間が勿体無いので不変の場合は先に書いておく. animation.ArtistAnimation †plot や pcolor などの描画コマンドが返すものをステップごとにひとつの変数に追加していく. fig = plt.figure()
ax = fig.add_subplot(111)
snap = []
for istep in np.arange(Nstart, Nend, 1):
if istep != 0:
ax.clear()
PC = plt.pcolor(X, Y, C[istep,:,:])
PC.set_clim(0.,1.) # 着色範囲の固定 (ここでは0〜1)
# plt.pause(.01) # 1コマずつ確認
snap.append([PC])
ani = animation.ArtistAnimation(fig, snap)
ani.save('filename.gif',writer='XXX',fps=num1,dpi=num2)
タイトルの変更がステップごとに反映されないため,時刻等をタイトル位置に示したい時には使えない. |