freedom-_-qの勉強履歴

メモ書きが主になるかと思います。勉強強制のために一日一記事目指してます。頭良くないので間違いが多々あるかと思います。

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.PathCollectionax.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()

f:id:freedom-_-q:20210617231952g:plain

お馴染みの動く点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')

f:id:freedom-_-q:20210617231826g:plain