如何正确启用 matplotlib.animation 的 ffmpeg?

matplotlibpythondata visualization

要启用 ffmpeg for matplotlib.animation,我们可以采取以下步骤 −

  • 设置图形大小并调整子图之间和周围的填充。

  • 设置 ffmpeg 目录。

  • 使用 figure() 方法创建新图形或激活现有图形。

  • 'ax1' 添加到图形作为子图布置的一部分。

  • 根据预先存在的轴绘制分隔线。

  • 创建要绘制的随机数据,以将数据显示为图像,即在 2D 常规栅格上。

  • ScalarMappable 实例 cb 创建颜色条。

  • 将标题设置为当前帧。

  • 创建颜色图列表。

  • 通过反复调用函数 animate 来制作动画。该函数创建新的随机数据,然后使用 imshow() 方法将数据显示为图像。

  • 获取基于 Pipe 的 ffmpeg 编写器的实例。

  • 保存当前动画图形。

示例

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.axes_grid1 import make_axes_locatable

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
plt.rcParams['animation.ffmpeg_path'] = 'ffmpeg'

fig = plt.figure()
ax = fig.add_subplot(111)
div = make_axes_locatable(ax)
cax = div.append_axes('right', '5%', '5%')
data = np.random.rand(5, 5)
im = ax.imshow(data)
cb = fig.colorbar(im, cax=cax)
tx = ax.set_title('Frame 0')

cmap = ["copper", 'RdBu_r&39;, 'Oranges&39;, 'cividis&39;, 'hot&39;, 'plasma&39;]

def animate(i):
   cax.cla()
   data = np.random.rand(5, 5)
   im = ax.imshow(data, cmap=cmap[i%len(cmap)])
   fig.colorbar(im, cax=cax)
   tx.set_text('Frame {0}'.format(i))

ani = animation.FuncAnimation(fig, animate, frames=10)
FFwriter = animation.FFMpegWriter()
ani.save('plot.mp4', writer=FFwriter)

输出

当我们执行代码时,它将创建一个名为"plot.mp4"的 mp4 文件并将其保存在项目目录中。


相关文章