2017-03-01 85 views
0

我想使用imshow animate using ArtistAnimation的示例,以便为从文件中获得的2D数组序列创建动画。为了做到这一点,我需要在一个函数内部使用ArtistAnimation,但是这个简单的改变给了我一个我不明白的TypeError。我做的修改是:异常类型错误使用Matplotlib imshow动画使用ArtistAnimation

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 




def f(x, y): 
    return np.sin(x) + np.cos(y) 

x = np.linspace(0, 2 * np.pi, 120) 
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1) 
# ims is a list of lists, each row is a list of artists to draw in the 
# current frame; here we are just animating one artist, the image, in 
# each frame 
def animate(x,y): 
    fig = plt.figure() 
    ims = [] 
    for i in range(60): 
     x += np.pi/15. 
     y += np.pi/20. 
     im = plt.imshow(f(x, y), animated=True) 
     ims.append([im]) 


    ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True, 
           repeat_delay=1000) 

    # ani.save('dynamic_images.mp4') 

    plt.show() 

我收到类型错误信息是:

In [23]: animate(x,y) 
Exception TypeError: TypeError("'instancemethod' object is not connected",) in <bound method TimerQT.__del__ of <matplotlib.backends.backend_qt5.TimerQT object at 0x7f964ea06150>> ignored 
+0

你在这里展示的代码几乎没有任何意义。改变例子的原因是什么? – ImportanceOfBeingErnest

回答

2

正如animation documentation说:“关键是要保持到实例对象的引用”。
另外,您最后还需要拨打plt.show()
虽然这不是当被运行的脚本中的问题,在jupyter笔记本你需要的代码更改为类似

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 


def f(x, y): 
    return np.sin(x) + np.cos(y) 

x = np.linspace(0, 2 * np.pi, 120) 
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1) 

def animate(x,y): 
    fig = plt.figure() 
    ims = [] 
    for i in range(60): 
     x += np.pi/15. 
     y += np.pi/20. 
     im = plt.imshow(f(x, y), animated=True) 
     ims.append([im]) 

    ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True, 
           repeat_delay=1000) 

    return ani 

,然后调用它像

ani = animate(x,y) 
plt.show() 

到保留对动画的引用。