LoginSignup
115
100

More than 5 years have passed since last update.

matplotlibのanimation.FuncAnimationを用いて柔軟にアニメーション作成

Last updated at Posted at 2016-10-25

pythonのmatplotlibには、

  • animation.FuncAnimation

という柔軟にアニメーションを作成することが出来る関数が存在する。
この関数の使用方法。

サンプルプログラム

sample_animation.py
import matplotlib.animation as anm
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize = (10, 6))
x = np.arange(0, 10, 0.1)

def update(i, fig_title, A):
    if i != 0:
        plt.cla()                      # 現在描写されているグラフを消去

    y = A * np.sin(x - i)
    plt.plot(x, y, "r")
    plt.title(fig_title + 'i=' + str(i))


ani = anm.FuncAnimation(fig, update, fargs = ('Initial Animation! ', 2.0), \
    interval = 100, frames = 132)

ani.save("Sample.gif", writer = 'imagemagick')

以上のコードを実行すれば、以下のようなアニメーションのファイル"Sample.gif"が生成されるはず。
Animation.gif

サンプルプログラムの解説

肝となるのは

ani = anm.FuncAnimation(fig, update, fargs = ('Initial Animation! ', 2.0), \
    interval = 100, frames = 132)

の一文。

第1引数 fig

figureオブジェクト。このオブジェクトに、図(アニメーション)に関する命令を与えていく。

第2引数 update

アニメーションを構成する図1枚1枚を作成するコールバック関数。
アニメーションを作成するということは複数の図を作成してそれをつなぎ合わせるということであるが、FuncAnimation関数では、それを「図を作成する関数を複数回呼び出す」という方法で実現している。
update関数の決まりは以下の通り。

  • FuncAnimation関数よりも前で定義しておく。
  • 2回目以降にこの関数が呼び出されるときに、図が初期化されるようにしておく。
    • 上記サンプルプログラムのplt.cla()の部分がそれに対応
  • この関数には少なくとも1つ引数を設ける。
    • この関数の第1引数(上記サンプルプログラムではi)は、この関数が呼び出される毎に0から1ずつ増えていく整数である。
    • この関数に2つ以上の引数を設けたい場合には、fargsで指定してやる(後述)。

オプション fargs

第2引数のupdate関数に2つ以上の引数を設けたい場合に、2つ目以降の引数を指定することが出来るオプション。
上記のサンプルプログラムの例だと、update関数の第2引数fig_title"Initial Animation!"が、第3引数A2.0がそれぞれ渡される。

オプション interval

アニメーションで図が切り替わる時間間隔を指定することが出来る(単位はミリ秒)。
interval = 100 とすると、「100ミリ秒に1回図が切り替わる」ようになる。

オプション frames

update関数を呼び出す回数を指定する。
frames = 132 とすると、update関数は132回呼び出され、これによって生成されたgifアニメは132枚の静止画を繋ぎ合わせたものになる。
(update関数の第1引数のiはその間0,1,...,131の値をとる)

参考URL

115
100
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
115
100