Matplotlib animation¶

Matplotlibを使ってグラフの時間発展を見る方法.

  • matplotlib.animation.FuncAnimationを使う.
  • バックエンドとしてinlineのままで動画にできるよう,HTML関数を使う.
  • 重たい処理のグラフ(seaborn.kdeplot)の上に,軽い処理のグラフ(plt.plot)を重ねて表示したい場合を考えている.
  • コードのいくつかはChatGPT-3.5 Turboの出力を拝借.
In [3]:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.animation import FuncAnimation
from IPython.display import HTML
In [8]:
# Generate random data for the KDE plot
data = np.random.multivariate_normal([0, 0], [[1, 0.5], [0.5, 1]], size=1000)

# Generate random data for moving points
n_points = 100
points = np.random.rand(n_points, 2) * 4 - 2  # within range [-2, 2]
In [12]:
np.set_printoptions(precision=3, floatmode='fixed')
sns.set_theme(context='talk', style='ticks')

fig, ax = plt.subplots(figsize=(5,5))
kde = sns.kdeplot(x=data[:,0], y=data[:,1], cmap="Reds", 
                  fill=True, ax=ax)
line, = plt.plot([], [], 'b-', alpha=.5)

def update(frame):
    # Update the line plot with the new points
    line.set_data(points[:frame, 0], points[:frame, 1])

ani = FuncAnimation(fig, update, 
                    frames=range(n_points), interval=100, 
                    repeat=False)
HTML(ani.to_html5_video())
Out[12]:
Your browser does not support the video tag.
No description has been provided for this image
In [ ]: