2017-03-01 87 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() 

到保留對動畫的引用。