Using matplotlib library can quickly draw some moving pictures, very convenient, in order to use these, you need to import
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
The core class is
animation.FuncAnimation
Here are animation.FuncAnimation
some constructed parameters:
fig : 画布对象
func : 更新函数,这个函数的入口是当前帧,方便用户更新点
init_func : 初始化函数,每次动画开始时调用
frames : 一次循环包含的帧序列,这个序列会被依次传入func更新函数中
interval : 迭代时间间隔(ms),越小越快
In order to initialize a moving point animation, we need the following steps
Create a sequence of points, which will be the trajectory of the moving point
len = 100
x = np.arange(0, len)
y = x
Create canvas, set canvas width and height (according to coordinate value setting)
len = 100
fig = plt.figure()
plt.xlim(-1,len+1)
plt.ylim(-1,len+1)
Create the artist object of the moving point. The initial coordinate is indexed at 0. This object will be updated by animation later. It is worth noting that the comma cannot be omitted because animation requires a sequence of artist.
p, = plt.plot(x[0], y[0], "o")
Write an initialization / update function, where initialization is to set the coordinates of the 0 subscript, and the update function is to receive the incoming frame sequence, update the coordinates of the point, and return the artist object sequence to be updated. The comma cannot also be omitted
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,
Create an animation object, and call the save method of the animation object, we can generate an animation
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)
Complete code
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)