LoginSignup
10
9

More than 5 years have passed since last update.

matplotlib.animationを利用してgif画像を作る (ArtistAnimation)

Last updated at Posted at 2018-10-27

matplotlibはデータ解析の可視化ツールとして一般的に用いられています.

今回は,matplotlib.animation機能を使ってgif画像を作ってみたので,そのコードを紹介します.
最終的には,以下のgifアニメーションを作りたいとします.

test.gif

matplotlib.animationには,「ArtistAnimation」機能「FuncAnimation」機能があります.
今回は「ArtistAnimation」機能で話を進めます.
「FuncAnimation」機能については,こちらのページでまとめています.
matplotlib.animationを利用してgif画像を作る (FuncAnimation)

なお,こちらのページも参考にしています.
+ Animation using matplotlib with subplots and ArtistAnimation

動作環境

  • Ubuntu
  • Anaconda3(Python3.6.6)
  • anaconda

Subplot機能を用いずにgif画像を生成

ArtistAnimationの考え方は,用意したリストに画像をappendして,繋ぎ合わせる事で連続画像(gif)にします.以下のgifアニメーションを作りたいとします.

test.gif

コードは以下の通りです.


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

fig = plt.figure() #figure objectを取得.
ax = fig.add_subplot(111)

x = np.arange(0,10,1)

ims = [] #Line2D objectを入れるリストを用意
for time in range(x.shape[0]):
    im = ax.plot(x[0:time] ,x[0:time] ** 2) #Line2D objectを取得
    ims.append(im) #imsにappendする

#ArtistAnimation機能で,imsの中の画像を繋ぎ合わせる.
ani = animation.ArtistAnimation(fig, ims, interval = 100)

#imagemagickを使って,gif画像を保存
ani.save("test.gif", writer="imagemagick")

figure objectと,Line2D objectが入ったリストを用意すれば,簡単に作れます.
なお,intervalは画像の表示間隔を調整するargumentです.

subplot機能と組み合わせて使う.

さて,本題です.
次は2つの画像をsubplotで表示して,gifアニメーションを作成します.

test.gif


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

fig, (ax1, ax2) = plt.subplots(2,1)

x = np.arange(0,10,1)

ims = []
for time in range(x.shape[0]):
    #im1の後ろに「,」を付けること
    im1, = ax1.plot(x[0:time], x[0:time] ** 2, color = 'forestgreen' )
    #im2の後ろに「,」を付けること
    im2, = ax2.plot(x[0:time], -x[0:time] ** 2 + 100, color = 'darkred' )
    #[im1,im2] というリストをimsにappendする事.
    ims.append([im1, im2])

ani = animation.ArtistAnimation(fig, ims, interval=500)
ani.save("test.gif", writer="imagemagick")

注意点として,im,やim2,のように「,」を付けるのを忘れないようにしましょう.

まとめ

animation機能を使えば,計算過程を可視化出来たるすると思います.
相手にも伝わりやすくなるかもしれません.

10
9
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
10
9