FuncAnimation是基于函数的动画类,它通过重复调用同一函数来制作动画。 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,否则将无法显示动画。
该方法常用参数的含义如下。
fig:表示动画所在的画布。
artists:表示一组 Artist对象的列表。
interval:表示更新动画的频率, 以毫秒为单位, 默认为200。
repeat_delay:表示再次播放动画之前延迟的时长。
repeat:表示是否重复播放动画。
%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
#绘制正弦曲线
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
#创建画布和坐标系
fig = plt.figure(tight_layout=True)
ax = fig.add_subplot(111)
#绘制正弦曲线
ax.plot(x, y,color='blue')
#动画设计
def update_points(num): #定义了一个update_points函数,用于更新绘制的图中的数据点,此函数的输入参数num代表当前动画的第几帧。
point_ani.set_data(x[num], y[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("C:\\图片\\a.gif", writer='pillow')
#展示图表
plt.show()
运行代码及展示结果