在matplotlib中动画抖动



我遵循了一些建议的代码来回答这个问题,在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()

但是当我运行这个时,我看到第一帧,没有任何更新

当我运行脚本时,我看到了您所描述的行为,并且在我运行它的终端中,我得到了一个带有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()

最新更新