はしくれエンジニアもどきのメモ

情報系技術・哲学・デザインなどの勉強メモ・備忘録です。

matplotlib のanimation を保存

matplotlib のanimation を保存

matplotlib のグラフは、 matplotlib.animation を使うことでアニメーションにすることできる。 そのアニメーション(動画)の保存についてメモ。

環境

  • Windows 10

    • conda 4.05

      • python 3.5.1

      • matplotlib 1.5.1

      • jupyter 4.1.0

matplotlib.animation の保存

matplotlib.animation.save() 関数で保存できる。

mp4の場合

mp4 であれば、 ffmpegMencoder をインストールしてPATHを通しておけば保存できる。


animation.save('hoge.mp4')

gif の場合

ffmpeg だけではgif の保存はできず、image magick を 介して使うようです。

  1. まず、image magick をインストールする。 chocolatey にもある。

    
    # powershell
    
    Install-Package imagemagick
    
  2. matplotlib の設定ファイルにimagemagick のパスを追加する。 以下のコマンドで、matplotlib の設定ファイルの場所をまず確認。 おそらくWindows のminiconda でインストールしているとほぼ同じ構成だと思います。

    
    # python
    
    import matplotlib
    matplotlib.matplotlib_fname()
    > 'C:\\Miniconda3\\lib\\site-packages\\matplotlib\\mpl-data\\matplotlibrc'
    
  3. 「matplotlibrc」を開いて一番下を見ると、 'animation.convert_path' の項目がコメントアウトされているので有効にして、imagemagic のコマンドのパスを追加。

    
    animation.convert_path:  C:\Program Files\ImageMagick-7.0.1-Q16\magick.exe
    

    ImageMagick はver7 からconvert コマンドからmagick コマンドに名前が変わったようです。

以上の設定をし、.save() の 引数writerimagemagick にすることでgif画像の保存ができる。


animation.save('hoge.gif', writer='imagemagick')

実行例

以下のsin波をシフトするアニメーションをgifで保存する。


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

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

ims = []
for a in range(50):
    y = np.sin(x - a)
    im = plt.plot(x, y, "b")
    ims.append(im)

ani = animation.ArtistAnimation(fig, ims)
ani.save('sample.gif', writer='imagemagick')

sin波アニメーション