python - 如何将 FuncAnimation(来自 matplotlib.animation 的动态绘图)配置为 numpy 数组?

标签 python dynamic matplotlib pde

我对 MatPlotLibFuncAnimation 函数有一些疑问。我无法将它配置到我的代码中...我希望有人能帮助我!!

这是一个扩散方程,我需要为时间的每一步绘制它。在每一步,计算的结果都是一个 numpy 数组。我设法用 pyplot.interactive(True) 以动态方式绘制它,但它非常慢。我读到 FuncAnimation 可以处理这个问题,但我没有设法让它处理列表或数组中的结果。

这是带有经典慢情节的代码:
它产生一个向量向量 (U),在所有计算之后绘制

import numpy as np
import scipy
from scipy.linalg import solve_banded
from matplotlib import pyplot as plt
import matplotlib.animation as animation


def DrawRecord(U):
    plt.interactive(True)
    plt.figure(1)
    for i in range(0,len(U)):
        plt.clf()
        plt.plot(U[i])
        plt.ylim([0,1])
        plt.draw()

J=350.0 
dt=0.01 
T=3.0 
t=np.arange(dt,T,dt) 
dx=1.0/J 

D=0.005 
c=0.5 
r=0.1 

mu=c*dt/(2.0*dx) 
lambd=D*dt/(dx**2.0) 

K_x=50.0*np.ones(J-1) 
alpha_t=0.5*np.ones(len(t)) 

#initial conditions
u=np.zeros(J) 
u[J/5*1:J/5*2]=1 
U=u

espace=np.linspace(0,1,J) 

#Matrix
A=np.diag(-lambd*np.ones(J-2),1)+np.diag((1+2*lambd)*np.ones(J-1),0)+np.diag(-lambd*np.ones(J-2),-1)  
AA=scipy.linalg.inv(A)


for i in t:

    u[1:J]=scipy.dot(AA,u[1:J]+(r-alpha_t[i/dt])*dt*(u[1:J]-u[1:J]/K_x))
    u[0]=0 
    u[J-1]=0  

    U=np.vstack([U,u])

DrawRecord(U)

下面是我尝试使用之前的代码来制作 FuncAnimation(大失败):
nb : U 包含为每个步骤计算的结果数组

global U

fig = plt.figure()
window = fig.add_subplot(111)
line, = window.plot(list(U[1,:]))

def init():
    line=list(U[1,:])
    return line

def animate(i):
    line.set_ydata(list(U[i,:]))
    return line

anim = animation.FuncAnimation(fig, animate, init_func=init,
                           frames=200, interval=20, blit=True)

plt.show()

这会产生很多错误......也许有人可以为以前的代码设置它!
我希望我清楚(对不起我的英语)并感谢您的帮助。

最佳答案

FuncAnimation 期望一个可迭代对象从 init 返回并更新

试试这个:

def init():
    line.set_ydata(U[1,:])
    return line,

关于python - 如何将 FuncAnimation(来自 matplotlib.animation 的动态绘图)配置为 numpy 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13387031/

相关文章:

python - 使用文件方法在多个文件中编辑一行 - python

python - 在 Python 中使用 ImageDraw.Draw(image) 循环会产生重叠文本

python - PyQT 4 fnished() 信号不会发出

python - matplotlib 中带有颜色渐变的箭头

python - mlxtendplot_decision_regions 模型适合 Pandas DataFrame?

jquery - 右对齐表格中的数值和 <thead>

c - 在 C 中实现动态调整堆栈大小的最佳方法是什么?

css - symfony 2动态更新配色方案

python - matplotlib imshow 显示比例固定为正方形

python - 从图 matplotlib 返回可 blit 的 numpy 数组