作者:上面的代码中,首先定义了一个update_points函数,用于更新绘制的图中的数据点。此函数的输入参数num代表当前动画的第几帧,函数的返回,即为我们需要更新的对象,需要特别注意的是:reuturn point_ani,这个逗号一定加上,否则动画不能正常显示。当然这里面操作的点对象point_ani我们一般会提前声明得到:point_ani, = plt.plot(x[0], y[0], "ro")。接下来就是将此函数传入我们的FuncAnimation函数中,函数的参数说明可以参见官网,这里简要说明用到的几个参数。
- 第1个参数fig:即为我们的绘图对象.
- 第2个参数update_points:更新动画的函数.
- 第3个参数np.arrange(0, 100):动画帧数,这需要是一个可迭代的对象。
- interval参数:动画的时间间隔。
- blit参数:是否开启某种动画的渲染。
运行上面代码可以得到如图2-2所示的动画效果。
2.3 往动画中添加其它效果
上面实现的动画效果还比较单一,我们可以往其中添加一些文本显示,或者在不同的条件下改变点样式。这其实也非常简单,只需在update_points函数中添加一些额外的,你想要的效果代码即可。
def update_points(num): if num%5==0: point_ani.set_marker("*") point_ani.set_markersize(12) else: point_ani.set_marker("o") point_ani.set_markersize(8) 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, x = np.linspace(0, 2*np.pi, 100) y = np.sin(x) fig = plt.figure(tight_layout=True) plt.plot(x,y) point_ani, = plt.plot(x[0], y[0], "ro") plt.grid(ls="--") text_pt = plt.text(4, 0.8, '', fontsize=16) ani = animation.FuncAnimation(fig, update_points, np.arange(0, 100), interval=100, blit=True) # ani.save('sin_test3.gif', writer='imagemagick', fps=10) plt.show()我在上面update_points函数中添加了一个文本,让它显示点的的坐标值,同时在不同的帧,改变了点的形状,让它在5的倍数帧显示为五角星形状。
