17
13

More than 5 years have passed since last update.

matplotlibのArtistAnimationで二つ以上のアニメーションを描く方法

Last updated at Posted at 2017-10-16

はじめに

matplotlibのArtistAnimationで二つのグラフのアニメーションを作ろうと四苦八苦していたのだが、やっと解決方法が見つかったのでここに記しておく。

ソースコード

結論からいうと、一つずつ描いたグラフを+演算子で足し合わせればそれでOK。また、plt.legend()の記述を一回だけにしないとグラフ内の凡例の数が描画回数の分だけ増えてしまうので注意。

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

fig = plt.figure()
ims = []
flag_legend = True#凡例描画のフラグ
#30step分だけsin,cosを少しずつ動かしながら描画する
for i in range(30):
    x = np.arange(-5,5,0.1)
    sin = np.sin(x+i*0.1)
    cos = np.cos(x+i*0.1)
    im1 = plt.plot(x,sin,label="sin_curve",color="red")
    im2 = plt.plot(x,cos,label="cos_curve",color="blue")
    if flag_legend:#一回のみ凡例を描画
        plt.legend()
        flag_legend = False
    ims.append(im1+im2)#グラフを配列に追加

ani = animation.ArtistAnimation(fig, ims, interval=100)#100ms ごとに表示
ani.save("output.html", writer="imagemagick")

結果

うまくいけばhtmlファイルが出力されて、こんな感じの画面がでます。この画面でボタンを触ればアニメーションが動きます。今回はアニメーション部分だけを抽出してgifにしたやつも一緒に載せておきます。

htmlの画面

animation_ss.png

gifアニメーション

anime.gif

さいごに

gifで保存しようとするとエラーなぜか出て、htmかhtmlで保存しろって言われます。解決方法がわかる人が教えて欲しい...(たぶんTkaggとかバックエンドの問題だと思うけど、調査しきれていない)

追記(※2017/10/25)

ubuntuで実行してみたところ、gifでの保存に成功しました。
pythonやモジュールのバージョン,matplotlibのバックエンドはMacのものとバージョンを合わせてあるので、ますます原因がわからなくなりました。

17
13
1

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
17
13