Skip to content Skip to sidebar Skip to footer

Matplotlib Artistanimation: Plot Entire Figure In Each Step

I have an existing function I use for plotting, which I call repeatedly in my program. I want to use matplotlib's ArtistAnimation to save each plot as an 'artist' that is shown in

Solution 1:

Instead of saving the axes, you need to save the plots as a list. (Or maybe you don't want to do this and want to save the axes? If that's the case, let me know and I'll delete this. I don't think saving the axes will work though, since the animation works by setting the saved items within a figure visible and invisible, and neither the axes nor the figure will hide/reveal a subset of the plots for each frame in this way.)

import matplotlib.pyplot as plt
from matplotlib import animation
import random

defmy_plot(ax):
    p0, = ax.plot([random.randrange(10), random.randrange(10)], [random.randrange(10), random.randrange(10)])
    p1, = ax.plot([random.randrange(10), random.randrange(10)], [random.randrange(10), random.randrange(10)])
    return [p0, p1]   # return a list of the new plots

ims = []
fig = plt.figure()
ax = fig.add_subplot(111)  # fig and axes created oncefor _ inrange(10):
    ps = my_plot(ax)
    ims.append(ps)      # append the new list of plots
ani = animation.ArtistAnimation(fig, ims, repeat=False)
ani.save('im.mp4', metadata={'artist':'Guido'})

GIF below, but here is some vertical spacing so you can scroll the annoying flashing lines of the page while reading the code

. . . . . . . . . . . . . .

enter image description here

Solution 2:

Thanks to tom's answer, I found the main reasons why my animations didn't work and only showed the first frame: I called plt.show() in each iteration. Apparently, after the first call, the animations stop working. Removing plt.show() and only creating one figure solved the problem:

import matplotlib.pyplot as plt
from matplotlib import animation
import random

defmy_plot():
    patch = []
    patch.extend(plot([random.randrange(10), random.randrange(10)], [random.randrange(10), random.randrange(10)]))
    patch.extend(plt.plot([random.randrange(10), random.randrange(10)], [random.randrange(10), random.randrange(10)]))
    # no plt.show() here!return patch

ims = []
fig = plt.figure()   # fig created only oncefor _ inrange(10):
    patch = my_plot()
    ims.append(patch)  
ani = animation.ArtistAnimation(fig, ims, repeat=False)
ani.save('im.mp4', metadata={'artist':'Guido'})

Not sure how I could both plot and show the plots directly and create an animation. Maybe using plt.draw() instead? But that doesn't show anything in my PyCharm IDE... Anyways, I can live with either or.

Post a Comment for "Matplotlib Artistanimation: Plot Entire Figure In Each Step"