Saving a gif file Python

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…

  • Maybe click edit and add some very, very simple code that creates multiple frames – even if they are just a solid red, a green and a blue frame. Then folks who know ImageMagick but not matplotlib will maybe be able to assist you.

    – 

  • It gives an error, “NameError: name ‘copy’ is not defined” on line config_copy = copy.deepcopy(config)

    – 

  • 1

    config is missing we need mre stackoverflow.com/help/minimal-reproducible-example

    – 

  • try using writer = ‘ffmpeg’

    – 

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)

Leave a Comment