前回の記事でグラフをアニメーションにするArtistAnimationについて解説した。
前回の記事でこんな感じのコードでグラフのアニメーションを作成した。
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation fig = plt.figure(figsize=(5,5))#グラフの作成 ax = fig.add_subplot(111)#subplotの作成 ims = [] for n in np.arange(100): im = ax.plot(n, n, marker=".", color="#555555", markersize=50) ims.append(im)#二つをまとめて足す ani = animation.ArtistAnimation(fig, ims, interval=1) ani.save("sample.gif", writer="imagemagick")
で、これax.plotでグラフを書いているのだけれど、
ax.scatterにしたらこんなエラーが出た
for n in np.arange(100): im_s = ax.scatter(n, n, marker=".") ims_s.append(im_s) ani = animation.ArtistAnimation(fig, ims_s, interval=1)
>> CalledProcessError: Command '['C:\\Program Files\\ImageMagick-7.0.8-Q16\\magick.exe', '-size', '360x360', '-depth', '8', '-delay', '0.1', '-loop', '0', 'rgba:-', 'sample2.gif']' returned non-zero exit status 1.
これいったいなんなのかというと
ax.plotはリストの状態でax.scatterはオブジェクトをそのまま帰すことが原因だった。
アニメーションにするためのグラフはリスト内リスト形式なので、ax.scatterはリストに入れてから追加する必要がある
ということで、こういう形でコードを変えると解決した。
for n in np.arange(100): im_s = ax.scatter(n, n, marker=".") ims_s.append([im_s]) #リストに入れてからims_sに追加
ani = animation.ArtistAnimation(fig, ims_s, interval=1)
さらに格納の仕方を工夫すれば、plotとscatterを同時に動かす事も出来る。これのおかげで非常に自由度の高いグラフが作れる。
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation fig = plt.figure(figsize=(5,5))#グラフの作成 ax = fig.add_subplot(111)#subplotの作成 ims = [] for n in np.arange(100): im_p = ax.plot([0,n], [0,n], marker=".", color="#555555", markersize=10) im_s = ax.scatter(100-n, n, marker=".", color="#555555", s=500) ims.append(im_p+[im_s])#それぞれの形式に合わせた形で格納
ani = animation.ArtistAnimation(fig, ims, interval=1) ani.save("sample_1.gif", writer="imagemagick")
[blog:g:11696248318754550880:banner][blog:g:11696248318755499803:banner]