如何在 Matplotlib 中为线图制作动画?
matplotlibpythondata visualization更新于 2025/5/20 14:04:17
要在 matplotlib 中为线图制作动画,我们可以采取以下步骤 −
使用 subplots() 方法创建一个图形和一组子图。
限制 x 和 y 轴的比例。
使用 numpy 创建 x 和 t 数据点。
从坐标向量 X2 和 T2 返回坐标矩阵。
使用 plot() 方法绘制带有 x 和 F 数据点的线。
要制作动画图,请更新 y 数据。
通过重复调用函数 *func*、当前图、动画,和间隔。
要显示图形,请使用show()方法。
示例
import numpy as np
from matplotlib import pyplot as plt, animation
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
ax.set(xlim=(-3, 3), ylim=(-1, 1))
x = np.linspace(-3, 3, 91)
t = np.linspace(1, 25, 30)
X2, T2 = np.meshgrid(x, t)
sinT2 = np.sin(2 * np.pi * T2 / T2.max())
F = 0.9 * sinT2 * np.sinc(X2 * (1 + sinT2))
line, = ax.plot(x, F[0, :], color='k', lw=2)
def animate(i):
line.set_ydata(F[i, :])
anim = animation.FuncAnimation(fig, animate, interval=100, frames=len(t) - 1)
anim.save('503.gif')
plt.show()
输出
当我们执行此代码时,它将显示带有动画的线图。

相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

