Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Matplotlib saved gif looping

Environment:

  • Matplotlib v2.2.2

Code:

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()

Output: It only play once.

enter image description here

like image 661
Honghe.Wu Avatar asked Jul 25 '18 06:07

Honghe.Wu


People also ask

How do I make a GIF loop continuously?

Loop a part of an animated GIF image Move the slider or play head across the timeline and press the 'S' key on your keyboard. Or you can right-click and choose 'Split'. Right-click on the other clips and select 'Delete'. You can now add the same GIF file and repeat the process to create a loop.

Can you animate Matplotlib?

Animations in Matplotlib can be made by using the Animation class in two ways: By calling a function over and over: It uses a predefined function which when ran again and again creates an animation. By using fixed objects: Some animated artistic objects when combined with others yield an animation scene.


1 Answers

Using imagemagick as a writer produces a looping gif, but I can't tell you why that does not work with PillowWriter

ani.save("demo2.gif", writer='imagemagick')

enter image description here

like image 77
Diziet Asahi Avatar answered Sep 27 '22 16:09

Diziet Asahi