Python Matplotlib 动态绘图:使用 Animation 创建动画实时正弦波
Python Matplotlib 动态绘图:使用 Animation 创建动画实时正弦波
本篇文章以动态正弦波为例,详细讲解了如何使用 Matplotlib 的 Animation
模块构建逐帧更新的动画效果。文章从动画核心函数 FuncAnimation
的原理入手,介绍了动画帧的定义、初始化函数的设置以及帧数据的动态更新方式。通过逐帧更新正弦波的 Y 数据,展示了如何让波形看起来像在动态传播。此外,文章还演示了如何将生成的动画保存为高质量的 MP4 视频文件,方便分享和播放。读者可以通过本文学习如何制作动态波形图、数据流展示和实时模拟图表。完整代码和丰富注释为入门和进阶用户提供了清晰的实现思路,是学习 Python 动态绘图的理想参考。
一 动画效果
在本文中,我们将使用 Matplotlib 的 Animation
模块来创建一个正弦波的动态展示,展示如何通过逐帧更新实现动画效果。
def animate(i, line, x):
# 更新线条的Y数据,使得正弦波随时间动态变化
line.set_ydata(np.sin(x + i / 10.0))
return line,
# 初始化动画,设置初始状态
def init(line, x):
# 初始化线条数据,使其不显示任何东西(通过mask实现)
line.set_ydata(np.ma.array(x, mask=True))
return line,
动画函数 animate
:animate
函数用于在每帧调用时更新正弦波的 Y 轴数据,从而实现波形的动态变化。通过修改表达式 x + i / 10.0
中的 i
(当前帧编号),正弦波看起来会随着时间逐步向右移动。
初始化函数 init
:init
函数用于动画开始前设置初始状态。通过掩码隐藏所有数据点,以确保初始帧不会显示残影。
# 创建图形和坐标轴
fig, ax = plt.subplots()
# 0~2π内的正弦曲线
x = np.arange(0, 2 * np.pi, 0.01) # 创建x数据,用于绘制正弦波
line, = ax.plot(x, np.sin(x)) # 绘制初始正弦波
# 创建动画
ani = animation.FuncAnimation(fig=fig,
func=lambda i: animate(i, line, x), # 指定动画函数
frames=np.arange(1, 200), # 设置动画帧数
init_func=lambda: init(line, x), # 指定初始化函数
interval=20, # 设置更新间隔(毫秒)
blit=False) # blit=True时仅重绘变化部分以提高效率,但在此设为False以保证兼容性
# 保存动画
ani.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
# 显示图形
plt.show()
在上面的代码中,FuncAnimation
类创建了一个动画对象,它会在设定的帧数内重复调用 animate
函数,每帧之间间隔 20 毫秒。整个动画最终被保存为 MP4 格式的文件,使用 H.264 编解码器,以便在视频播放器中观看。
注意事项
ani.save
保存MP4格式的视频文件使用 matplotlib
的 animation
模块,通常需要在系统上安装 FFmpeg。FFmpeg 是一个强大的多媒体框架,能够解码、编码、转码、复用、解复用、流处理、过滤和播放几乎所有类型的视频和音频文件,
1 Windows 安装 FFmpeg
从 FFmpeg 官方网站 下载 FFmpeg 的二进制文件。
2 macOS 安装 FFmpeg
$ brew install ffmpeg
3 Linux 安装 FFmpeg
例如,在 Ubuntu 或 Debian 上,可以使用:
$ sudo apt update
$ sudo apt install ffmpeg
二 静态图
三 动画展示
四 完整代码示例
# This is a sample Python script.
# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np
def animate(i, line, x):
# 更新线条的Y数据,使得正弦波随时间动态变化
line.set_ydata(np.sin(x + i / 10.0))
return line,
# 初始化动画,设置初始状态
def init(line, x):
# 初始化线条数据,使其不显示任何东西(通过mask实现)
line.set_ydata(np.ma.array(x, mask=True))
return line,
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press ⌘F8 to toggle the breakpoint.
# 创建图形和坐标轴
fig, ax = plt.subplots()
x = np.arange(0, 2 * np.pi, 0.01) # 创建x数据,用于绘制正弦波
line, = ax.plot(x, np.sin(x)) # 绘制初始正弦波
# 创建动画
ani = animation.FuncAnimation(fig=fig,
func=lambda i: animate(i, line, x), # 指定动画函数
frames=np.arange(1, 200), # 设置动画帧数
init_func=lambda: init(line, x), # 指定初始化函数
interval=20, # 设置更新间隔(毫秒)
blit=False) # blit=True时仅重绘变化部分以提高效率,但在此设为False以保证兼容性
# 保存动画
ani.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
# 显示图形
plt.show()
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('Animation 动画')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
复制粘贴并覆盖到你的 main.py 中运行,运行结果如下。
Hi, Animation 动画
五 源码地址
代码地址:
国内看 Gitee 之 matplotlib/Animation 动画.py
国外看 GitHub 之 matplotlib/Animation 动画.py
六 参考
[1] Matplotlib 官网
[2] 莫烦 python
[3] Matplotlib 简单动画
作者:敲代码不忘补水