matplotlib.animation.ArtistAnimationで遊ぶ
はじめに
若干ハマりそうになる箇所があるから記録しておく。 あまり詳しく調べてないから間違ってるかも。
基本構文
Animation
の引数fig
にはmatplotlib.figure.Figure
, artists
にはmatplotlib.collections.PathCollection
のリストのリストを指定する。
artists
に渡すオブジェクトは以下のようなイメージ。
[ [matplotlib.collections.PathCollection, ...], # 1フレーム目 [matplotlib.collections.PathCollection, ...], # 2フレーム目 [matplotlib.collections.PathCollection, ...], # 3フレーム目 ... ]
matplotlib.collections.PathCollection
はax.scatter
などの戻り値。
乱数を散布図に表示
# 必須ライブラリのインポート import matplotlib.pyplot as plt from matplotlib.animation import ArtistAnimation from matplotlib import rcParams rcParams['font.family'] = 'Meiryo' fig, ax = plt.subplots() artists = [] # 10枚の散布図を生成 for _ in range(10): xy = np.random.randn(2,100) artists.append([ax.scatter(*xy)]) #アニメーション作成 ArtistAnimation(fig, artists) # IPythonの場合、plt.show()まで続けて書くと上手くいかない。 plt.show()
お馴染みの動く点P
マジックナンバー多いけど、ヨシッ!
import matplotlib.patches as patches import numpy as np from matplotlib.animation import PillowWriter fig, ax = plt.subplots() artists = [] for p_x in np.arange(0, 5 + 0.1, 0.1): xy = np.array( ((0, 0), (0, 4), (p_x, 0))) ax.set_xlim(-1, 6) ax.set_ylim(-1, 5) artist = [ax.add_patch(patches.Rectangle((0, 0), 5, 4, fill=False)), ax.add_patch(patches.Polygon(xy)), ax.scatter(p_x, 0, color='black'), ax.text(p_x + 0.1, 0 + 0.1, '点P')] artists.append(artist) ani = ArtistAnimation(fig, artists, interval=100) ani.save('moving_point.gif', writer='PillowWriter')