Matplotlib ArtistAnimation给出TypeError:'AxesImage'对象不可迭代

时间:2013-08-02 14:19:56

标签: python animation matplotlib

你能帮我解决一下这个问题吗?我不知道出了什么问题。来自img的单个图可以很好地绘制,但动画模块会给出错误。 Traceback说:

Traceback (most recent call last):
  File "/home/ckropla/workspace/TAMM/Sandkasten.py", line 33, in <module>
    ani = animation.ArtistAnimation(fig, img, interval=20, blit=True,repeat_delay=0)
  File "/home/ckropla/.pythonbrew/pythons/Python-3.3.1/lib/python3.3/site-packages/matplotlib/animation.py", line 818, in __init__
    TimedAnimation.__init__(self, fig, *args, **kwargs)
  File "/home/ckropla/.pythonbrew/pythons/Python-3.3.1/lib/python3.3/site-packages/matplotlib/animation.py", line 762, in __init__
    *args, **kwargs)
  File "/home/ckropla/.pythonbrew/pythons/Python-3.3.1/lib/python3.3/site-packages/matplotlib/animation.py", line 481, in __init__
    self._init_draw()
  File "/home/ckropla/.pythonbrew/pythons/Python-3.3.1/lib/python3.3/site-packages/matplotlib/animation.py", line 824, in _init_draw
    for artist in f:
TypeError: 'AxesImage' object is not iterable

代码:

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

def FUNCTION(p,r,t):
    k_0,dx,c = p
    x,y = r
    z = np.exp(1j*(k_0[0]*np.meshgrid(x,y)[0]+k_0[1]*np.meshgrid(x,y)[1]-c*t))*np.exp(-((np.sqrt(np.meshgrid(x,y)[0]**2+np.meshgrid(x,y)[1]**2)-c*t)/(2*dx))**2 )*(2/np.pi/dx**2)**(1/4)
    z = abs(z)
    #k,F = FFT((x-c*t),y)
    return(x,y,z)

#Parameter
N = 500
n = 20
x   = np.linspace(-10,10,N)
y   = np.linspace(-10,10,N)
t = np.linspace(0,30,n)
r=[x,y]
k_0 = [1,1]
dx  = 1
c   = 1
p = [k_0,dx,c]

fig = plt.figure("Moving Wavepackage")

Z   = []
img = []
for i in range(n):
    Z.append(FUNCTION(p,r,t[i])[2])
    img.append(plt.imshow(Z[i]))

ani = animation.ArtistAnimation(fig, img, interval=20, blit=True,repeat_delay=0)

plt.show()

1 个答案:

答案 0 :(得分:19)

img中的每个元素都需要是艺术家的序列,而不是单个艺术家。如果您将img.append(plt.imshow(Z[i]))更改为img.append([plt.imshow(Z[i])]),那么您的代码就可以正常使用。