Exception TypeError使用Matplotlib imshow使用ArtistAnimation进行动画处理

时间:2017-03-01 10:11:14

标签: python animation matplotlib typeerror

我正在尝试使用imshow animate using ArtistAnimation的示例来动画我从文件中获取的2D数组序列。为了做到这一点,我需要在函数内部使用ArtistAnimation,但是这个简单的更改给了我一个我不理解的TypeError。我做的修改是:

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()

我收到的TypeError消息是:

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

1 个答案:

答案 0 :(得分: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()

保持对动画的引用。