简体   繁体   中英

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: 在此输入图像描述

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'])

Check out this tutorial on animation in matplotlib. http://nbviewer.ipython.org/urls/raw.github.com/jakevdp/matplotlib_pydata2013/master/notebooks/05_Animations.ipynb

A quick search shows how to create an animation as mp4, you can then convert it with a third-party tool to a format you desire.

from matplotlib import animation

# call the animator.  
...
anim = animation.FuncAnimation(fig, animate, init_func=init,
                           frames=200, interval=20, blit=True)
...
anim.save('basic_animation.mp4', fps=30)

As simple but effective solution is to use pylab.savefig(filename) in the loop and save a file for each frame, ie right after pylab.draw() . The filenames should reflect the loop index, ie 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.

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