

新闻资讯
技术学院Matplotlib动画核心是FuncAnimation复用绘图对象并逐帧更新数据。需先创建初始图形,定义update函数用set_data等刷新,固定坐标轴防跳动,保存时依格式安装Pillow或ffmpeg。
用 Matplotlib 做动画其实不难,关键是理清 帧更新逻辑 和 绘图对象复用机制。Matplotlib 动画本质是按时间顺序反复修改已有图形元素(比如线条、散点、文本),而不是每帧重画整个图——这样才够快、才可控。
核心是 matplotlib.animation.FuncAnimation,它定时调用你写的更新函数,把新数据“喂”给已存在的绘图对象。
line, = ax.plot([], []))def update(frame):),在里面用 set_data() 或 set_ydata() 等方法刷新数据frames=range(N) 控制总帧数,interval=50 设定毫秒级间隔(即每 50ms 更新一帧)anim = FuncAnimation(fig, update, frames=..., interval=...) 启动动画直接显示用 plt.show();保存成 GIF 或 MP4 需额外依赖。常见组合:
anim.save("demo.gif", writer="pillow")
anim.save("demo.mp4", writer="ffmpeg")
matplotlib.rcParams["animation.html"] = "jshtml",再在 Jupyter 中直接显示交互式动画动态可视化不是炫技,而是传递信息。几个关键细节:
ax.set_xlim() 和 ax.set_ylim() 固定坐标轴范围,防止画面跳动干扰观察趋势line1.set_data()、line2.set_data()
ax.text() 创建一次,再在 update 函数里用 text.set_text(f"Step: {frame}") 刷新复制粘贴就能跑,理解结构后可快速改造成自己的场景:
import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots() x = np.linspace(0, 2*np.pi, 100) line, = ax.plot(x, np.sin(x)) ax.set_ylim(-1.2, 1.2)
def update(frame): x_shifted = (x + frame 0.1) % (2np.pi) y = np.sin(x_shifted) line.set_ydata(y) return line,
anim = FuncAnimation(fig, update, frames=200, interval=50, blit=True) plt.show()