首页 > 解决方案 > 保存在python中的for循环内创建的动画

问题描述

我有这个示例代码,它可以工作。我对 python 真的很陌生,我来自 Matlab 和 Octave。我需要在 FOR 循环中操作变量(以与给定示例不同且更复杂的方式),然后我需要 gif 文件中的动画输出。使用此代码,我可以使用所需的 fps 正确地可视化动画,但是我无法找到一种简单的方法来将 plt.show() 时看到的动画保存到 gif 文件或多个 png 文件中。我该怎么做?

# basic animated mod 39 wheel in python


import matplotlib.pyplot as plt
import numpy as np 
plt.close()
plt.rcParams.update({
    "lines.color": "white",
    "patch.edgecolor": "white",
    "text.color": "lightgray",
    "axes.facecolor": "black",
    "axes.edgecolor": "lightgray",
    "axes.labelcolor": "white",
    "xtick.color": "white",
    "ytick.color": "white",
    "grid.color": "lightgray",
    "figure.facecolor": "black",
    "figure.edgecolor": "black",
    "savefig.facecolor": "black",
    "savefig.edgecolor": "black"})
plt.xlabel('real axis')
plt.ylabel('imaginary axis')
plt.title('events constellation')
plt.xlim(-4, 4)
plt.ylim(-4, 4)
plt.gca().set_aspect('equal', adjustable='box')
plt.draw()
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()

for n in range(1,40):

    cnums = 3 * np.exp(1j * 2 * np.pi * (1/39) * n)
    x = cnums.real 
    y = cnums.imag 
    plt.scatter(x, y , label="event", marker="o", color="red", s=200)
    plt.pause(1)

plt.show()


标签: pythonanimation

解决方案


您可以使用非常简单的赛璐珞包从 matplotlib 动画中制作视频。https://github.com/jwkvam/celluloid

最小的例子:

from matplotlib import pyplot as plt
from celluloid import Camera

fig = plt.figure()
camera = Camera(fig)
for i in range(10):
    plt.plot([i] * 10)
    camera.snap()
animation = camera.animate()
animation.save('output.gif')

推荐阅读