matplotlib 動画・アニメーション作成

主な手法は2つらしい.
加えて,imagemagick の convert を Python から使う方法もあるよう.下のリンクは参考.
Matplotlib の pause を使ったアニメーションを簡単に動画にできる Python スクリプト matplotrecorder

個人的には画像で掃き出して動画は ffmpeg コマンドにしているが,ここではあえて Python で動画を作成する.
インポートは下記の通り.

import matplotlib.pyplot as plt
import matplotlib.animation as animation

animation.FuncAnimation

ArtistAnimationは タイトルを動的に設定できない?ため,FuncAnimation を使いたい.
このコマンドでは,各ステップに対応する描画 function を作成する必要がある.下記の update_pcolor に相当.
また,その function の第一入力引数は,時間ステップを示すものでなければならない.
下記は pcolor で書いて,gif で保存するときのサンプル.

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.FuncAnimation の2番目の入力引数には,function 名をそのまま記述する.
その function(update_pcolor) の引数は,第二引数以降から fargs=(...) で挿入する.
update_pcolor の第一引数は,frames の数にしたがって順番に勝手に入力されるため,入力する必要はない.
frames=10 とすると,istep=0〜9 までのものを書く.
interval で1フレーム当たりの表示時間(ms)を指定できる.

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)

タイトルの変更がステップごとに反映されないため,時刻等をタイトル位置に示したい時には使えない.


Front page   Edit Diff Attach Copy Rename Reload   New List of pages Search Recent changes   Help   RSS of recent changes
Last-modified: 2018-02-15 (Thu) 05:38:57 (2261d)