【Python】matplotlibでアニメーションgifを作るための環境構築

matplotlib.animationでアニメーションgifを作成する方法。

目次

1. ImageMagickのインストール

ImageMagickというソフトが必要なので、以下のサイトからインストーラーをダウンロードしてインストールを行う。
http://www.imagemagick.org/script/download.php#windows

今回は、Windows環境なので、ImageMagick-7.0.8-36-Q16-x64-dll.exeを使用した。

2. matplotlibrcファイルの編集

次に、
matplotlib にImageMagickのパスを通す必要があるので、matplotlibrcの中身にImageMagickの実行ファイルのパスを追加する。
matplotlibrc ファイルは、C:\ProgramData\Anaconda3\Lib\site-packages\matplotlib\mpl-dataの中にある。


matplotlibrc ファイルをテキストエディタ等で開くと、最下方に
#animation.convert_path: ‘convert’ …..
という一行がある。ここにImageMagickの実行ファイルのフルパスに直す。
animation.convert_path: C:\Program Files\ImageMagick-7.0.8-Q16\magick.exeとする。ちなみに、もともと書いてあった
#animation.convert_path: ‘convert’ ….. は消去してしまってよい。また、行の先頭にあった#は不要である。

実際にコードを書いてみる

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)
     line, = plt.plot(x, y, "r")
     ims.append([line])

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

plt.show()

結果

spyder上ので表示はおかしいような気もしたが、無事anim.gifファイルが出力された。

ちなみに、ani.save(‘anim.mp4’, writer=”ffmpeg”)で動画ファイルで保存してみようと思ったが、UserWarning: MovieWriter ffmpeg unavailableというエラーが表示された。ImageMagickをインストールする際、
ffmpeg も一緒にインストールしたはずなのに正しく動かないようだ。

コメント

タイトルとURLをコピーしました