简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM