如何使 Matplotlib 保存的 gif 循环

Hon*_*.Wu 9 loops matplotlib gif

环境:

  • Matplotlib v2.2.2

代码:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.animation import PillowWriter

fig = plt.figure()

def f(x, y):
    return np.sin(x) + np.cos(y)

x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
# ims is a list of lists, each row is a list of artists to draw in the
# current frame; here we are just animating one artist, the image, in
# each frame
ims = []
for i in range(20):
    x += np.pi / 15.
    y += np.pi / 20.
    im = plt.imshow(f(x, y))
    ims.append([im])

ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True,
                                repeat_delay=500)

writer = PillowWriter(fps=20)
ani.save("demo2.gif", writer=writer)

plt.show()
Run Code Online (Sandbox Code Playgroud)

输出:它只播放一次。

在此处输入图片说明

Diz*_*ahi 9

imagemagick作为作家使用会产生一个循环的 gif,但我不能告诉你为什么这不起作用PillowWriter

ani.save("demo2.gif", writer='imagemagick')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明