Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 737
Coolcrab Avatar asked Aug 25 '26 10:08

Coolcrab


2 Answers

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'])
like image 100
Coolcrab Avatar answered Aug 27 '26 01:08

Coolcrab


As simple but effective solution is to use pylab.savefig(filename) in the loop and save a file for each frame, i.e. right after pylab.draw(). The filenames should reflect the loop index, i.e. frame0001.png, frame0002.png, … Then use FFmpeg (http://www.ffmpeg.org/) to stitch them together. There is already a question and an answer how this works (Create animated gif from a set of jpeg images). FFmpeg has a lot of options. For example, you can adjust the frame rate.

like image 44
Mike Müller Avatar answered Aug 27 '26 02:08

Mike Müller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!