1.FuncAnimation类
FuncAnimation (fig, func, frames=None, init_func=None, fargs=None,
save_count=None, *, cache_frame_data=True, **kwargs)
fig:表示动画所在的画布。
func:表示每帧动画调用的函数。
frames:表示动画的长度(一次动画包含的帧数)。
init_func:表示用于开始绘制帧的函数,它会在第一帧动画之前调用一次。若未设置该参数,则程序将使用frames序列中第一项的绘图结果。
fargs:表示传递给func函数的其他参数。
interval:表示更新动画的频率,以毫秒为单位,默认为200。(1秒=1000毫秒)
blit:表示是否更新所有的点,默认为False。官方推荐将blit参数设为True,建议 macOS 的用户将blit参数设为False,否则将无法显示动画。
2.ArtistAnimation类
ArtistAnimation (fig, artist,interval,repeat_delay,repeat,blit,
*args,**kwargs)
fig:表示动画所在的画布
artist:表示一组Artist对象的列表
interval:表示更新动画的频率,以毫秒为单位,默认200
repeat_delay:表示在次播放动画之前延迟的时长
repeat:表示是否重复播放动画
FuncAnimation类创建动画,代码如下:
#导入模块
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
plt.rcParams["font.sans-serif"] = ["SimHei"]#设置中文
plt.rcParams["axes.unicode_minus"] = False
# 1. 准备正弦曲线数据
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
fig = plt.figure(tight_layout=True)#紧凑布局,使图像更美观
ax = fig.add_subplot(111)#创建画布格局1行1列,绘制在1
ax.plot(x, y,color='purple')
def update_points(num):
point_ani.set_data(x[num], y[num]) # num代表当前动画第几帧
text_pt.set_text("x=%.3f, y=%.3f"%(x[num], y[num]))
return point_ani,text_pt,
plt.plot(x,y)
point_ani, = plt.plot(x[0], y[0], "ro")
text_pt = plt.text(4, 0.8, '', fontsize=16)
ani = animation.FuncAnimation(fig, update_points, np.arange(0, 100), interval=100, blit=True)
#将动画保存为gif图片
ani.save("pratice7.3.gif", writer='pillow')
plt.show()
运行结果: