Animation的概述:Animation类是一个动画基类。其中,FuncAnimation类表示基于重复调用一个函数的动画;ArtistAnimation类表示基于一组Artist(标准的绘图元素,比如文本、线条、矩形等)对象的动画。具体说明如下:
2. ArtistAnimation 类
ArtistAnimation 是基于一组Artist对象的动画类,它通过一帧一帧的数据制作动画。ArtistAnimation类的构造方法的语法格式如下所示:
ArtistAnimation(fig, artists, interval, repeat_delay, repeat, blit, *args, **kwargs)
该方法常用参数的含义如下。
·fig:表示动画所在的画布。
·artists:表示一组 Artist对象的列表。
·interval:表示更新动画的频率, 以毫秒为单位, 默认为200。
·repeat_delay:表示再次播放动画之前延迟的时长。
·repeat:表示是否重复播放动画。
FuncAnimation是基于函数的动作类,它通过重复通用同一函数来制作动画。FuncAnimation类的构造方法的语法格式如下所示:
该方法常用函数的含义如下。
fig:表示动画所在的画布。
func:表示每帧动画调用的函数。
frames:表示动画的长度(一次动画包含的帧数)。
init_func:表示用于开始绘制帧的函数,它会在第一帧动画之前调用一次。若未设置该参数,则程序将使用frames序列中第一项的绘图结果。
fargs:表示传递给func函数的其他参数。
interval:表示更新动画的频率,以毫秒为单位,默认为200。
blit:表示是否更新所有的点,默认为False。官方推荐将blit参数设为True,但建议macOS的用户将blit参数设为False,否则将无法显示动画。
2. ArtistAnimation 类
ArtistAnimation 是基于一组Artist对象的动画类,它通过一帧一帧的数据制作动画。ArtistAnimation类的构造方法的语法格式如下所示:
该方法常用参数的含义如下。
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("D:\\图片\\a.gif", writer='pillow')
#展示图表
plt.show()
#运行程序,效果如图: