要求如下:(1)绘制一条正弦曲线;
(2)绘制一个红色圆点,该圆点最初位置位于正弦曲线的左端,animation()函数;
(3)制作一个圆点沿曲线运动的动画并时刻显示圆点的坐标位置;
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# 0. 设置中文黑体
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
# 1. 准备正弦曲线数据
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
# 2. 创建画布和坐标系
fig = plt.figure(tight_layout=True)
ax = fig.add_subplot(111)
# 3. 绘制正弦曲线
plt.plot(x,y)
point_ani, = plt.plot(x[0], y[0], "ro")
text_pt = plt.text(4, 0.8, '', fontsize=16)
# 4. 动画设计
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
# 5.开始制作动画
ani = animation.FuncAnimation(fig, update_points, np.arange(0, 100), interval=100, blit=True)
·fig:即为我们的绘图对象;
·frames=100, 动画的帧数,这里是100帧;
·interval是指新动画的频率,间隔越大,动画越慢,1s=1000ms;
·blit:只更新当前点,不是全部,True则是更新全部画面 ;
# 6.将动画保存为gif图片
ani.save("pratice7.3.gif", writer='pillow')
# 7.展示图表
plt.show()
效果图如下: