matplotlib imshow():如何动画?

时间:2013-06-20 11:42:02

标签: image animation matplotlib

我找到了这个关于动画的精彩短篇教程:

http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/

然而,我无法制作同样时尚的动画imshow()情节。 我试图替换一些行:

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 10), ylim=(0, 10))
#line, = ax.plot([], [], lw=2)
a=np.random.random((5,5))
im=plt.imshow(a,interpolation='none')
# initialization function: plot the background of each frame
def init():
    im.set_data(np.random.random((5,5)))
    return im

# animation function.  This is called sequentially
def animate(i):
    a=im.get_array()
    a=a*np.exp(-0.001*i)    # exponential decay of the values
    im.set_array(a)
    return im

但我遇到了错误 你能帮助我这个跑步吗? 先感谢您。 最好,

2 个答案:

答案 0 :(得分:15)

你非常接近,但有一个错误 - initanimate应该返回 iterables ,其中包含正在制作动画的艺术家。这就是为什么在Jake的版本中他们返回line,(实际上是一个元组)而不是line(这是一个单行对象)。可悲的是,文档对此并不清楚!

您可以像这样修复您的版本:

# initialization function: plot the background of each frame
def init():
    im.set_data(np.random.random((5,5)))
    return [im]

# animation function.  This is called sequentially
def animate(i):
    a=im.get_array()
    a=a*np.exp(-0.001*i)    # exponential decay of the values
    im.set_array(a)
    return [im]

答案 1 :(得分:2)

这是一个完整的例子:

# Usually we use `%matplotlib inline`. However we need `notebook` for the anim to render in the notebook.
%matplotlib notebook

import random
import numpy as np

import matplotlib
import matplotlib.pyplot as plt

import matplotlib.animation as animation


fps = 30
nSeconds = 5
snapshots = [ np.random.rand(5,5) for _ in range( nSeconds * fps ) ]

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure( figsize=(8,8) )

a = snapshots[0]
im = plt.imshow(a, interpolation='none', aspect='auto', vmin=0, vmax=1)

def animate_func(i):
    if i % fps == 0:
        print( '.', end ='' )

    im.set_array(snapshots[i])
    return [im]

anim = animation.FuncAnimation(
                               fig, 
                               animate_func, 
                               frames = nSeconds * fps,
                               interval = 1000 / fps, # in ms
                               )

anim.save('test_anim.mp4', fps=fps, extra_args=['-vcodec', 'libx264'])

print('Done!')

# plt.show()  # Not required, it seems!