[matplotlib animation] 5. Decay(軸の更新アニメーション)

matplotlib Animation

はじめに

matplotlibのanimationにおける軸の更新について解説する。

コード

このコードをjupyter notebookで実行しても軸が更新されない。
xmaxは160になっているので、ax.figure.canvas.draw()が機能してない様子。
機能しない原因はdata_genだろうと考えて、data_genをなくしたコードを以下に作成した。

解説

moduleのインポート

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML

HTMLはjupyter notebook上にアニメーションを表示するためにimport.

fig, plotの作成

fig, ax = plt.subplots()
line, = ax.plot([], [], lw=2)
xdata, ydata = [], []

figとaxを設定。
line,には、空のデータでlw(線幅)を2にしてプロット
xdata, ydataはそれぞれ空のリスト。

データの生成

t=np.linspace(0,100,1000)
y=np.sin(2*np.pi*t) * np.exp(-t/10.)

data_genから引っ張り出してきたもの。
tは0〜100の等間隔な1000個の配列。
yはそのtを使って求めた値。

アニメーションの初期設定

def init():
ax.set_ylim(-1.1, 1.1)
ax.set_xlim(0, 10)
del xdata[:]
del ydata[:]
line.set_data(xdata, ydata)
return line,

set_xlim, set_ylimでx軸、y軸の表示範囲の設定。
del xdata[:]で、すでにxdataになにかあるときに備えて削除。
line.set_data(xdata, ydata)でデータをセット。
return line,でline,を返す。lineのあとには「,」がいる。

アニメーションの設定

def run(i,t,y):
# update the data
xdata.append(t[i])
ydata.append(y[i])
line.set_data(xdata, ydata)

.sppendでx,yにデータを順次加えていく。
.set_dataでline(plot)にデータを加えていく。

軸の更新

    xmin, xmax = ax.get_xlim()
if t >= xmax:
        ax.set_xlim(xmin, 2*xmax)

現在のxminとxmaxを.get_xlim()で取得。
tがxmax以上ならば、x軸の最大値をxmax*2として拡張する。

アニメーションの表示

ani = animation.FuncAnimation(fig, run, 1000, fargs=(t,y), blit=False, interval=10,
repeat=False, init_func=init)
HTML(ani.to_html5_video())

FuncAnimationでアニメーションを表示。framesが1000でintervalが10なので、10 sのアニメーションとなる。repeat=Falseで繰り返し再生しなくなる。init_funcで初期設定。

コードをダウンロード(.pyファイル)

コードをダウンロード(.ipynbファイル)

参考

https://matplotlib.org/gallery/animation/animate_decay.html

コメント

  1. […] […]