我按照一些建议的代码回答了这个问题,Plotting animated quivers in Python,但我发现我遇到了一个问题没有解决。请考虑以下代码:
from matplotlib import pyplot as plt
import numpy as np
import matplotlib.animation as animation
def ufield(x,y,t):
return np.cos(x+y)*np.sin(t)
def vfield(x,y,t):
return np.sin(x+y)*np.cos(t)
x = np.linspace(0,10, num=11)
y = np.linspace(0,10, num=11)
X,Y = np.meshgrid(x,y)
t = np.linspace(0,1)
def update_quiver(j, ax, fig):
u = ufield(X,Y,t[j])
v = vfield(X,Y,t[j])
Q.set_UVC(u, v)
ax.set_title('$t$ = '+ str(t[j]))
return Q,
fig =plt.figure()
ax = fig.gca()
u = ufield(X,Y,t[0])
v = vfield(X,Y,t[0])
Q = ax.quiver(X, Y, u, v)
ax.set_title('$t$ = '+ str(t[0]))
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
ani = animation.FuncAnimation(fig, update_quiver,
frames = range(0,t.size),
interval=1,fargs=(ax, fig))
plt.show()
此代码运行正常,没有问题。但是,如果我想使用init_func,我会这样做,因为我想用动画做更多的事情,我试过了:
def init_quiver():
u = ufield(X,Y,t[0])
v = vfield(X,Y,t[0])
Q = ax.quiver(X, Y, u, v)
ax.set_title('$t$ = '+ str(t[0]))
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
return Q,
从脚本主体中删除这些行
u = ufield(X,Y,t[0])
v = vfield(X,Y,t[0])
Q = ax.quiver(X, Y, u, v)
并按如下方式更新动画行:
ani = animation.FuncAnimation(fig, update_quiver,
frames = range(0,t.size),
init_func=init_quiver,
interval=1,fargs=(ax, fig))
plt.show()
但是当我运行它时,我会看到第一帧,并且没有任何更新。
答案 0 :(得分:0)
当我运行你的脚本时,我看到你描述的行为,并且在我运行它的终端中,我收到一个带有Traceback结尾的错误:
File "quiv.py", line 21, in update_quiver Q.set_UVC(u, v) NameError: global name 'Q' is not defined
您可以通过添加行
来解决此问题global Q
作为init_quiver
函数的第一行。
完整的代码现在为:
from matplotlib import pyplot as plt
import numpy as np
import matplotlib.animation as animation
def ufield(x,y,t):
return np.cos(x+y)*np.sin(t)
def vfield(x,y,t):
return np.sin(x+y)*np.cos(t)
x = np.linspace(0,10, num=11)
y = np.linspace(0,10, num=11)
X,Y = np.meshgrid(x,y)
t = np.linspace(0,1)
def update_quiver(j, ax, fig):
u = ufield(X,Y,t[j])
v = vfield(X,Y,t[j])
Q.set_UVC(u, v)
ax.set_title('$t$ = '+ str(t[j]))
return Q,
def init_quiver():
global Q
u = ufield(X,Y,t[0])
v = vfield(X,Y,t[0])
Q = ax.quiver(X, Y, u, v)
ax.set_title('$t$ = '+ str(t[0]))
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
return Q,
fig =plt.figure()
ax = fig.gca()
ax.set_title('$t$ = '+ str(t[0]))
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
ani = animation.FuncAnimation(fig, update_quiver,
frames = range(0,t.size),
init_func=init_quiver,
interval=1,fargs=(ax, fig))
plt.show()