user27886
user27886

Reputation: 602

Python animation using matplotlib

I've been browsing docs, examples, and SO questions for hours now and still am unable to figure this out . I have the following python function:

def getPlotData(index)

Which returns 4 lists:

tPlots, yPlots, colorPlots, alphaPlots

Each element in each list contains

such that I could make individual image plots as such:

N = 100 #the details of how i have this number aren't important.
for frame in range(N):
    tPlots, yPlots, colorPlots, alphaPlots = getPlotData(frame)
    for i in range(len(tPlots)):
        plt.figure()
        plt.plot(tPlots[i],yPlots[i],color=colorPlots[i], alpha = alphaPlots[i])

plt.show()

but this of course generates static figures, one per frame. I would like to generate a movie from these frames, but the API for matplotlib is very confusing to me for animations/movies. There are many options to choose from and none seem simple. None of the ways seem inherently organized the way my functions produce frames. I've refactored getPlotData(index) 3 times now to try to get function usable by some of the matplotlib methods to no avail, although the currently 3rd-refactored form is the most useable (most modular).

The simplest approach seemed to be if I could just create a list of frames, but I have yet to succeed applying the above getPlotData(index) to this use case even from following this example.

Any ideas? Thank you.

EDIT: I just wanted to be clear, my intent is to save the movie to an mp4 or any other file format. I don't intend to run the python script later, just the movie file. Thank you.

Upvotes: 1

Views: 426

Answers (1)

Marcus Müller
Marcus Müller

Reputation: 36482

If you really just want to save things to a movie, and want to stick to matplotlib, no matter how bad it performs computationally:

  1. set up your figure: fig = pyplot.figure(figsize=(w,h), dpi=100) or so;
  2. do your drawing
  3. fig.savefig("{framenumber:06d}.png".format(framenumber=counter))
  4. rinse, repeat

and later use e.g. mencoder to convert to a movie:

mencoder -o output.mp4 -ovc mpeg4 *.png

Upvotes: 1

Related Questions