Saving a gif file Python

68 Views Asked by At

I'm trying to save an animation using the following code snippet:

import matplotlib.animation as animation 
import matplotlib.pyplot as plt 

import copy

......
frames = []

for i in range(500):
    config_copy = copy.deepcopy(config)
    frames.append((plt.imshow(config_copy, cmap='Greys_r', aspect=1,
         interpolation='none', vmin=-1, vmax=1), plt.scatter(loc[1], loc[0], c='red', marker='o', s=50)))
...
animation = FuncAnimation(f, lambda x: x, frames=frames, blit=True, interval=200)
animation.save('fun_animation_random_direction.gif', writer='imagemagick', fps=30)
plt.show()

When I run my code, the animation appears as it should be! But when I open the resulting gif file, I only see a picture which seems to show all frames at the same time. How can I resolve this issue?

I tried to open the gif file with other apps than the Windows photo viewer, but no success...

1

There are 1 best solutions below

0
Rohan On
import matplotlib.animation as animation 
import matplotlib.pyplot as plt 
import copy

# Assuming config and loc are defined and updated within the loop

frames = []

for i in range(500):
    # Assuming config and loc are updated within the loop
    config_copy = copy.deepcopy(config)  # Assuming config is updated in each iteration
    frames.append((plt.imshow(config_copy, cmap='Greys_r', aspect=1,
                    interpolation='none', vmin=-1, vmax=1), 
                    plt.scatter(loc[1], loc[0], c='red', marker='o', s=50)))

# Check if frames are correctly collected and if they represent the changes over time

# Show the animation before saving
fig, ax = plt.subplots()
ani = animation.ArtistAnimation(fig, frames, interval=200, blit=True)
plt.show()

# Save the animation using different parameters or writers
ani.save('fun_animation_random_direction.gif', writer='imagemagick', fps=30)