绘制一个具有动画效果的图表,具体要求如下:
(1) 绘制一条正弦曲线;
(2) 绘制一个红色圆点,该圆点最初位于正弦曲线的左端;
(3) 制作一个圆点沿曲线运动的动画,并时刻显示圆点的坐标位置。
1.导入模块
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.animation import FuncAnimation #导入FuncAnimation类显示动图
2.设置中文黑体
#2.设置中文黑体
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
3.准备正弦曲线数据
# 3.准备正弦曲线数据
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
4.创建画布和坐标系
#4.创建画布和坐标系
fig = plt.figure(tight_layout=True)
ax = fig.add_subplot(111)
5.绘制正弦曲线
#5.绘制正弦曲线
ax.plot(x, y)
point, = ax.plot(x[0], y[0], "ro") #创建红色圆点,将红色圆点设定在正弦曲线的最左端
coordinate = ax.text(4.2, 0.9, "", fontsize=16) #文本显示红色圆点经过正弦曲线函数每个点的坐标位置
6.动画设计
#6.动画设计
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)
FuncAnimation类(基于函数的动画类)
FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True, **kwargs)
FuncAnimation类常用参数的含义如下:
fig:表示动画所在的画布。
func:表示每帧动画调用的函数。
frames:表示动画的长度(一次动画包含的帧数)。
init_func:表示用于开始绘制帧的函数,它会在第一帧动画之前调用一次。若未设置该参数,则程序将使用frames序列中第一项的绘图结果。
fargs:表示传递给func函数的其他参数。
interval:表示更新动画的频率,以毫秒为单位,默认为200。
blit:表示是否更新所有的点,默认为False。官方推荐将blit参数设为True,但建议macOS的用户将blit参数设为False,否则将无法显示动画。
7.将动画保存为gif图片
#7.将动画保存为gif图片
ani.save("pratice7.3.gif", writer='pillow')
8.展示图表
#8.展示图表
plt.show()
整体代码:
#1.导入模块
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.animation import FuncAnimation #导入FuncAnimation类显示动图
#2.设置中文黑体
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
# 3.准备正弦曲线数据
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
#4.创建画布和坐标系
fig = plt.figure(tight_layout=True)
ax = fig.add_subplot(111)
#5.绘制正弦曲线
ax.plot(x, y)
point, = ax.plot(x[0], y[0], "ro") #创建红色圆点,将红色圆点设定在正弦曲线的最左端
coordinate = ax.text(4.2, 0.9, "", fontsize=16) #文本显示红色圆点经过正弦曲线函数每个点的坐标位置
#6.动画设计
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)
#7.将动画保存为gif图片
ani.save("pratice7.3.gif", writer='pillow')
#8.展示图表
plt.show()
运行结果: