在python中保存在for循环中创建的动画

2024-05-14 12:01:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个示例代码,它是有效的。我对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()



Tags: 文件代码示例np动画pltgifcolor
2条回答

如果你想导出图像,在黑板上有很多问题的答案。 例如:https://stackoverflow.com/a/9890599/6102332

如果要导出为gif或mp4等格式。 同样,论坛上也有很多很好的回复。 例如:https://stackoverflow.com/a/25143651/6102332


特别是关于您的代码: 如果要保存多个图像,可以将此行放在for循环的末尾:

for n in range(1, 10):
    cnums = 3 * np.exp(1j * 2 * np.pi * (1 / 39) * n)
    plt.scatter(cnums.real, cnums.imag, label="event", marker="o", color="red", s=200)
    plt.savefig(f'D:\\pic_{n}.png')

如果您想导出到gif:您应该了解有关ImageMagick、枕套书写器或imageio的更多信息。 在这里,我将示例imageio如下所示:

import matplotlib.pyplot as plt
import numpy as np
import imageio

fig, ax = plt.subplots()

ax.set(xlim=(-4, 4), ylim=(-4, 4))

red_dot = ax.scatter(None, None, color='red')


data = []


def plot_for_offset(n):
    cnums = 3 * np.exp(1j * 2 * np.pi * (1 / 39) * n)
    data.append([cnums.real, cnums.imag])
    red_dot.set_offsets(data)

    fig.canvas.draw()

    img = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8')
    img = img.reshape(fig.canvas.get_width_height()[::-1] + (3,))

    return img


imageio.mimsave(r'F:\red-dot.gif', [plot_for_offset(n) for n in range(1, 40)], fps=1)

这是gif图像: enter image description here

您可以使用非常简单的赛璐珞包来制作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')

相关问题 更多 >

    热门问题