Thomas Hopkins
Thomas Hopkins

Reputation: 691

Creating movie from a series of matplotlib plots using matplotlib.animation

I have a script which generates a series of time dependent plots. I'd like to "stitch" these together to make a movie.

I would preferably like to use matplotlib.animation. I have looked at examples from matplotlib documentation but I can't understand how it works.

My script currently makes 20 plots at successive time values and saves these as 00001.png up to 000020.png:

from scipy.integrate import odeint 
from numpy import *
from math import cos
import pylab

omega=1.4 
delta=0.1 
F=0.35 

def f(initial,t):  
    x,v=initial                 
    xdot=v
    vdot=x-x**3-delta*v-F*cos(omega*t)
    return array([xdot,vdot])


T=2*pi/omega 
nperiods = 100 
totalsteps= 1000
small=int((totalsteps)/nperiods)
ntransients= 10
initial=[-1,0] 


kArray= linspace(0,1,20)

for g in range (0,20):
    k=kArray[g]

    x,v=initial

    xpc=[]
    vpc=[]

    if k==0:
        x,v=x,v
    else:
        for i in range(1,nperiods)
            x,v=odeint(f,[x,v],linspace(0,k*T,small))[-1]   )

    for i in range (1,nperiods):
        x,v=odeint(f,[x,v],linspace(k*T,T+k*T,small))[-1] 
        xpc.append(x)  
        vpc.append(v)

    xpc=xpc[ntransients:]
    vpc=vpc[ntransients:]


    pylab.figure(17.8,10) 
    pylab.scatter(xpc,vpc,color='red',s=0.2)
    pylab.ylim([-1.5,1.5])
    pylab.xlim([-2,2])

    pylab.savefig('0000{0}.png'.format(g), dpi=200)

I'd appreciate any help. Thank you.

Upvotes: 0

Views: 7886

Answers (1)

MattDMo
MattDMo

Reputation: 102852

I think matplotlib.animation.FuncAnimation is what you're looking for. Basically, it repeatedly calls a defined function, passing in (optional) arguments as needed. This is exactly what you're already doing in your for g in range(0,20): code. You can also define an init function to get things set up. Check out the base class matplotlib.animation.Animation for more info on formats, saving, the MovieWriter class, etc.

Upvotes: 1

Related Questions