matplotlibライブラリを使用すると、いくつかの動画をすばやく描画できます。これを使用するには、インポートする必要があります。
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
コアクラスは
animation.FuncAnimation
animation.FuncAnimation
構築されたパラメータの一部を次に示します。
fig : 画布对象
func : 更新函数,这个函数的入口是当前帧,方便用户更新点
init_func : 初始化函数,每次动画开始时调用
frames : 一次循环包含的帧序列,这个序列会被依次传入func更新函数中
interval : 迭代时间间隔(ms),越小越快
移動点アニメーションを初期化するには、次の手順が必要です
一連の点を作成します。これは、移動する点の軌道になります
len = 100
x = np.arange(0, len)
y = x
キャンバスを作成し、キャンバスの幅と高さを設定します(座標値の設定に従って)
len = 100
fig = plt.figure()
plt.xlim(-1,len+1)
plt.ylim(-1,len+1)
移動するポイントのアーティストオブジェクトを作成します。初期座標のインデックスは0です。このオブジェクトは後でアニメーションによって更新されます。アニメーションにはアーティストのシーケンスが必要なため、コンマは省略できないことに注意してください。
p, = plt.plot(x[0], y[0], "o")
初期化/更新関数を記述します。初期化は0の添え字の座標を設定することであり、更新関数は着信フレームシーケンスを受け取り、ポイントの座標を更新し、更新するアーティストオブジェクトシーケンスを返すことです。カンマも省略できません
def update(frame):
print(frame)
p.set_data((x[frame]+1)%len, (y[frame]+1)%len)
return p,
def init():
p.set_data(x[0], y[0])
return p,
アニメーションオブジェクトを作成し、アニメーションオブジェクトのsaveメソッドを呼び出すと、アニメーションを生成できます
ani = animation.FuncAnimation(fig=fig,
func=update,
init_func=init,
frames=np.arange(0, len),
interval=10)
plt.show()
ani.save('1.gif', fps=30)
完全なコード
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
if __name__ == '__main__':
len = 100
x = np.arange(0, len)
y = x
fig = plt.figure()
plt.xlim(-1,len+1)
plt.ylim(-1,len+1)
p, = plt.plot(x[0], y[0], "o")
def update(frame):
print(frame)
p.set_data((x[frame]+1)%len, (y[frame]+1)%len)
return p,
def init():
p.set_data(x[0], y[0])
return p,
ani = animation.FuncAnimation(fig=fig, func=update, init_func=init, frames=np.arange(0, len), interval=10)
plt.show()
ani.save('1.gif', fps=30)