要求如下: (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)
创建红色小圆点,设计动画
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,
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
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()
运行结果