如何在 Matplotlib 中为正弦曲线制作动画?

matplotlibpythondata visualization

要制作动画正弦曲线,我们可以采取以下步骤 −

  • 设置图形大小并调整子图之间和周围的填充。
  • 创建一个新图形或激活现有图形。
  • 向当前图形添加轴并使其成为当前轴。
  • 用空列表绘制一条线。
  • 要初始化线条,请传递空列表。
  • 要为正弦曲线制作动画,请更新正弦曲线值并返回线条实例。
  • 要显示图形,请使用 show() 方法。

示例

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

def init():
   line.set_data([], [])
   return line,

def animate(i):
   x = np.linspace(0, 2, 1000)
   y = np.sin(2 * np.pi * (x - 0.01 * i))
   line.set_data(x, y)
   return line,

anim = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True)
plt.show()

输出


相关文章