用 matplotlib 制作在jupyter notebook 上即时显示的动态 gif 的简单代码

代码如下:

# encoding: utf-8

import pylab as plt
import numpy as np
from matplotlib import animation
from IPython.display import HTML
import tempfile

def animate(datalist, file_name=None, interval = 20, figsize=(3,3), **kwargs):
    fig, ax = plt.subplots(figsize=figsize)
    
    if file_name is None:
        file_name = tempfile.NamedTemporaryFile().name+'.gif'
    else:
        if file_name[-4:] != '.gif': file_name += '.gif'

    im = ax.imshow(datalist[0],**kwargs)
    
    def init():
        im.set_data(datalist[0])
        return im,

    def animate_gen(i):
        im.set_data(datalist[i])
        return im,
            
    anim = animation.FuncAnimation(fig, animate_gen, frames=len(datalist), init_func = init, interval=interval, blit=True)
    anim.save(file_name,writer='imagemagick')
    return HTML('<img src="'+file_name+'"></img>')

以下是一个应用实例的代码:

a=np.random.random((100,100))
ims = []
for i in range(20):
    ims.append(a)
    a = a*np.exp(-0.001*i)
animate(ims,file_name='animation1.gif')

以下是运行的结果:
animation1

完。

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s