python matplotlib 绘制sinx动画

python matplotlib 绘制sinx动画

"""
    绘制sin函数的动画
"""
import numpy as np
import matplotlib.pyplot as mp
import matplotlib.animation as ma

# 准备数据
x_t = np.linspace(0, 2 * np.pi, 500)
y = np.sin(x_t)

# 绘制图片
mp.figure("Sin(x) Animation", facecolor="lightgray")
mp.title("Sin(x) Animation", fontsize=18)
mp.xlim(0, 2 * np.pi + 1)
mp.ylim(-1.1, 1.1)

# 坐标轴 刻度
mp.xticks([0, np.pi / 2, np.pi, 3 * np.pi / 2, 2 * np.pi],
          ["0", r"$\frac{\pi}{2}$", r"$\pi$", r"$\frac{3\pi}{2}$", r"$2\pi$"])

# 坐标轴 控制与移动
ax = mp.gca()
ax.spines["top"].set_color("none")
ax.spines["right"].set_color("none")
ax.spines["bottom"].set_position(("data", 0))

pl = mp.plot([], [], c="r")[0]


# 更新数据
def update(number):
    index = number % 500
    pl.set_data(x_t[:index], y[:index])


# 创建动画对象 设置更新函数
anim = ma.FuncAnimation(mp.gcf(), update, interval=10)

mp.grid(linestyle=":")

mp.show()


python matplotlib 绘制sinx动画_第1张图片

你可能感兴趣的:(python)