一.animation概述
matplolib 在 1.1 版本的标准库中加入了动画模块——animation,以实现一些基本的动画效果。 animation类是一个动画基类,它针对不同的行为分别派生不同子类,主要包括 FuncAnimation 类和ArtistAnimatin类。具体说明如下,
1.FuncAnimation类
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,否则将无法显示动画。
2.ArtistAnimation类
ArtistAnimation是基于一组Artist对象的动画类,它通过一帧一帧的数据制作动画,ArtistAnimation类的构造方法的语法格式如下所示:
ArtistAnimation (fig, artist,interval,repeat_delay,repeat,blit,
*args,**kwargs)
该方法常用参数的含义如下:
fig:表示动画所在的画布
artist:表示一组Artist对象的列表
interval:表示更新动画的频率,以毫秒为单位,默认200
repeat_delay:表示在次播放动画之前延迟的时长
repeat:表示是否重复播放动画
两者间FuncAnimation类创建动画的方式更为灵活
熟悉以上含义后下面为实例:
绘制一个具有动画效果的图表,具体要求如下:
(1) 绘制一条正弦曲线;
(2) 绘制一个红色圆点,该圆点最初位于正弦曲线的左端;
(3) 制作一个圆点沿曲线运动的动画,并时刻显示圆点的坐标位置。
· 这里通过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
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()
其结果如下: