python
1animation.ArtistAnimation(fig, artists, *args, **kwargs)
- fig: Figure オブジェクト
- artists: 各フレームを構成する Artist の一覧
- interval: 各フレームの表示間隔 (ミリ秒)。デフォルトは 200 ms。
- repeat_delay: リピートする場合、リピートする前の遅延を ms で指定する。デフォルトは None。
- repeat: リピートするかどうか。デフォルトは True。
matplotlib でアニメーションを作成するポイント
- Figure、Axes を作成する。
- 各フレームで表示する Artist のリストを作成する。
[[フレーム1で表示する Artist], [フレーム2で表示する Artist]:
Axes.plot() などグラフ作成の関数は、それを構成する Artist を返すようになっているので、
それをリストに詰めていってください。
- ArtistAnimation() に渡す。
- ArtistAnimation.save() で保存する。
Ipython Notebook を利用している場合は、冒頭に以下を入れると、plt.show()
で Notebook 上に表示できます。
Artist とは
グラフを構成するオブジェクトです。
例えば、折れ線グラフは、Line2D という Artist で構成されています。
Axes.plot() などの関数は返り値として、そのグラフを構成する Artist を返すようになっています。
より詳しくは こちら や こちら
などを参考にしてください。
サンプルコード
python
1import matplotlib.pyplot as plt
2import numpy as np
3from matplotlib.animation import ArtistAnimation
4from mpl_toolkits.mplot3d import Axes3D
5from scipy.stats import multivariate_normal
6
7# (x, y) の点の一覧を作成する。
8x = np.linspace(-5, 5, 1000)
9y = np.linspace(-5, 5, 1000)
10X, Y = np.meshgrid(x, y)
11XY = np.c_[np.ravel(X), np.ravel(Y)]
12
13#############################################
14
15fig, axes = plt.subplots(figsize=(4, 4))
16frames = [] # 各フレームを構成する Artist 一覧
17
18for i in np.linspace(0, 4, 10):
19 # 2次元正規分布の値を生成する。
20 mean = np.array([i, i])
21 sigma = np.eye(2)
22 Z = multivariate_normal.pdf(x=XY, mean=mean, cov=sigma)
23 Z = Z.reshape(X.shape)
24
25 # 等高線グラフを作成する。
26 im = axes.contourf(X, Y, Z, 10, cmap=plt.cm.winter)
27
28 # 等高線を構成する Artist 一覧を追加する。
29 print(im) # matplotlib.contour.QuadContourSet object
30 artists = im.collections # QuadContourSet の collections 属性が Artist の一覧
31 frames.append(artists)
32
33# アニメーションを作成する。
34anim = ArtistAnimation(fig, frames, interval=500)
35
36# gif 画像として保存する。
37anim.save('animation.gif', writer='imagemagick')
38# mp4 で保存する場合は以下。ffmpeg がインストールされている必要がある。
39# anim.save('anim.mp4', writer='ffmpeg', fps=4)
40
41# Figure を表示する。
42fig.show()
43
実行すると、2次元正規分布の中心が少しずつ右上に移動していくアニメーションgifが作成されます。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/09/11 16:14