2013-10-12 74 views
9

我想要在Python中为诸如风的矢量创建动画。我试图在pylab中使用颤抖函数,并与来自matplotlib的matplotlib.animation一起使用。但结果说'QuiverKey' object is not subscriptable。我认为这是因为我不完全了解这两个功能,或者只是这两个功能不匹配。下面是我的代码,它实际上是来自matplotlib的颤音和动画函数之间的组合。在Python中绘制动画颤动者

def update_line(num, data, line): 
    line.set_data(data[...,:num]) 
    return line, 

X,Y = np.meshgrid(np.arange(0,2*np.pi,.2),np.arange(0,2*np.pi,.2)) 
U = np.cos(X) 
V = np.sin(Y) 

fig1 = plt.figure() 
Q = quiver(X[::3, ::3], Y[::3, ::3], U[::3, ::3], V[::3, ::3], 
     pivot='mid', color='r', units='inches') 
data = quiverkey(Q, 0.5, 0.03, 1, r'$1 \frac{m}{s}$', fontproperties={'weight': 'bold'}) 
plt.axis([-1, 7, -1, 7]) 
title('scales with plot width, not view') 
l, = plt.plot([], [], 'r-') 
plt.xlabel('x') 
plt.ylabel('y') 
plt.title('test') 
line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l), 
interval=50, blit=True) 
plt.show() 
+1

嘛,'data'是'QuiverKey'对象 - 这是一个关键的情节颤抖,而不是一个数组您可以编入索引的值。我真的不明白你的目标是什么 - 你说你想绘制动画颤抖,但是你的动画函数看起来只是为了添加点而已。你能描述你想要达到的目标吗? –

+0

嗨ali_m,我真的很感谢你的评论和帮助。我的目标是制作一个动画,让颤抖的人朝着箭头的方向移动。也许我对这个功能结构的理解太低了。你能帮我理解我如何让每个箭头移动到每个箭头(矢量)方向吗? – Isaac

+1

我还是不太明白你的意思。你想改变箭的长度和角度,还是你想要移动它们的支点?据我所知,一旦创建了颤动图,就没有办法改变颤抖图的x,y坐标,但是你可以使用'Q.set_UVC()'来更新箭头矢量。 –

回答

11

下面是一个例子,让你开始:

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

X, Y = np.mgrid[:2*np.pi:10j,:2*np.pi:5j] 
U = np.cos(X) 
V = np.sin(Y) 

fig, ax = plt.subplots(1,1) 
Q = ax.quiver(X, Y, U, V, pivot='mid', color='r', units='inches') 

ax.set_xlim(-1, 7) 
ax.set_ylim(-1, 7) 

def update_quiver(num, Q, X, Y): 
    """updates the horizontal and vertical vector components by a 
    fixed increment on each frame 
    """ 

    U = np.cos(X + num*0.1) 
    V = np.sin(Y + num*0.1) 

    Q.set_UVC(U,V) 

    return Q, 

# you need to set blit=False, or the first set of arrows never gets 
# cleared on subsequent frames 
anim = animation.FuncAnimation(fig, update_quiver, fargs=(Q, X, Y), 
           interval=50, blit=False) 
fig.tight_layout() 
plt.show() 

enter image description here