animation.FuncAnimation
函数的基本使用
调用函数animation.FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True, **kwargs)
来生成动态图。
animation:matplotlib在1.1版本的标准库中加入了动画模块——animation,使用该模块的Animation类可以实现一些基本的动画效果。Animation类是一个动画基类,它针对不同的行为分别派生了不同的子类,主要包括FuncAnimation类和Artist Animation类。其中,FuncAnimation类表示基于重复调用一个函数的动画;ArtistAnimation类表示基于一组固定Artist(标准的绘图元素,比如文本、线条、矩形等)对象的动画
实例:
绘制一个具有动画效果的图表,具体要求如下:
(1) 绘制一条正弦曲线;
(2) 绘制一个红色圆点,该圆点最初位于正弦曲线的左端;
(3) 制作一个圆点沿曲线运动的动画,并时刻显示圆点的坐标位置。
导入所需函数:
%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)
动画设计
创建一个圆点在曲线左端
更新文本内容为当前坐标位置
point, = ax.plot(x[0], y[0], "ro")
coordinate = ax.text(4.2, 0.9, "", fontsize=12)
def animation1(frame):
point.set_data(x[frame], y[frame]) # 更新圆点位置
coordinate.set_text(f"x={x[frame]:.3f}, y={y[frame]:.3f}") # 更新文本内容为当前坐标位置
return point, coordinate
ani = animation.FuncAnimation(fig=fig, func=animation1, frames=len(x), interval=100, blit=True)
set_data()函数用于设置绘图对象的数据,point是绘制红色圆点的对象
point.set_data(x[frame], y[frame]) :x的坐标为x[frame],y的坐标是y[frame]
point.set_data(x[frame], y[frame]):可以让圆点沿着正弦曲线的路径移动,并实现动画效果
展示图表
plt.show()
将动画保存为gif图片
ani.save("pratice7.3.gif", writer='pillow')
FuncAnimation类常用参数的含义如下:
fig:表示动画所在的画布。
func:表示每帧动画调用的函数。
frames:表示动画的长度(一次动画包含的帧数)。
init_func:表示用于开始绘制帧的函数,它会在第一帧动画之前调用一次。若未设置该参数,则程序将使用frames序列中第一项的绘图结果。
fargs:表示传递给func函数的其他参数。
interval:表示更新动画的频率,以毫秒为单位,默认为200。
blit:表示是否更新所有的点,默认为False。官方推荐将blit参数设为True,但建议macOS的用户将blit参数设为False,否则将无法显示动画。
全部代码如下
%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)
point, = ax.plot(x[0], y[0], "ro") # 创建一个圆点在曲线左端
coordinate = ax.text(4.2, 0.9, "", fontsize=12) # 创建文本对象用于显示坐标位置
def animation1(frame):
point.set_data(x[frame], y[frame]) # 更新圆点位置
coordinate.set_text(f"x={x[frame]:.3f}, y={y[frame]:.3f}") # 更新文本内容为当前坐标位置
return point, coordinate
ani = animation.FuncAnimation(fig=fig, func=animation1, frames=len(x), interval=100, blit=True)
plt.show()
ani.save('sin_test3.gif', writer='imagemagick', fps=10)
interval:更新动画的频率,1秒=1000毫秒
blit:表示是否更新所有点,默认为False