おいも貴婦人ブログ

生物系博士課程満期退学をしたAIエンジニアのブログ。

Pythonのmatplotlibを使ってアニメーションを作る。

matplotlibを使って、y=xの直線を引くアニメーションを作成しました。初めて使う機能はシンプルであればシンプルである程いいと思うので、ソースも出来るだけシンプルに書きました。

#! /usr/bin/env python
from matplotlib import animation as anim
import matplotlib.pyplot as plt

def event():
    x,y=0,0
    cnt=0
    while(cnt<20):
        yield x,y
        y+=1
        x+=1
        cnt+=1

fig=plt.figure()

def func():
    ax = fig.add_subplot(111)
    line, = ax.plot([], [], lw=2)
    ax.grid()
    xdata, ydata = [], []
    ax.set_ylim(0, 25)
    ax.set_xlim(0, 25)
    def f(data):
        x,y=data
        xdata.append(x)
        ydata.append(y)
        line.set_data(xdata,ydata)
        return line,
    return f

ani = anim.FuncAnimation(fig, func(), event, blit=True, interval=5, repeat=False)
ani.save('test_anim.mp4')