Search code examples
pythonmatplotlibplotanimated-gif

Animated graph to Animated Gif (Python)


I have made a simple n-body simulator and I plot/animate the movement with the following code:

for i in range(N):
    [...]
    x = [ Rbod[j][0], Rbod[j][0]]
    y = [ Rbod[j][1], Rbod[j][1]]
    #print(R1, V1, A1, F12)
    if i%10 == 0:
        print(i)
        pylab.ion()
        pylab.scatter( x, y, c=(j/nbodies,j/nbodies,j/nbodies) )
        pylab.axis([-400, 400, -400, 400])
        pylab.draw()

Now I would really like to save the animation as a gif. Is this possible? The internet vaguely said that it was but not on how to do it with pylab.

Example of 4 body interaction: enter image description here


Solution

  • I solved it by using ffmpeg, a conversion programme ran trough the commandline. So first I save all the seperate pictures and then make them into a avi and the avi into a gif.

                print(i)
                #pylab.ion()
                pylab.scatter( x, y, c=(j/nbodies,j/nbodies,j/nbodies) )
                pylab.axis([-400, 400, -400, 400])
                #pylab.draw()
                pylab.savefig('picture'+str(i))
    
    os.chdir('C://Users/Alex')
    subprocess.call(['ffmpeg', '-i', 'picture%d0.png', 'output.avi'])
    subprocess.call(['ffmpeg', '-i', 'output.avi', '-t', '5', 'out.gif'])