因此,我编写了一个简单的代码,使用Matplotlib的FuncAnimation创建动画图。但是没有输出。 我认为问题出在'np.append'函数中,因为如果我给'animate'函数提供预制的x,y,z数组,则代码可以正常工作。但是,我不明白为什么这行不通!
%matplotlib notebook
import numpy as np
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.pyplot as plt
import matplotlib.animation as animation
del_t = 0.01 ##Time-step value
x=np.array([0.0])
y=np.array([10.0])
z=np.array([0.0])
#These functions give how (x, y, z) co-ordinate
#changes with time
def dx_dt(x, y, z):
return 10*(y-x)
def dy_dt(x, y, z):
return -x*z + 28*x - y
def dz_dt(x, y, z):
return x*y-(8/3)*z
#Runge-Kutta Method for numerical solution of differential equations
#These functions give next (x, y, z) co-ordinate
def next_xpt(x, y, z):
k1 = dx_dt(x, y, z) * del_t
k2 = dx_dt(x + k1/2, y, z) * del_t
k3 = dx_dt(x + k2/2, y, z) * del_t
k4 = dx_dt(x + k3, y, z) * del_t
return x + (k1 + 2*k2 + 2*k3 + k4)/6
def next_ypt(x, y, z):
k1 = dy_dt(x, y, z) * del_t
k2 = dy_dt(x, y + k1/2, z) * del_t
k3 = dy_dt(x, y + k2/2, z) * del_t
k4 = dy_dt(x, y + k3, z) * del_t
return y + (k1 + 2*k2 + 2*k3 + k4)/6
def next_zpt(x, y, z):
k1 = dz_dt(x, y, z) * del_t
k2 = dz_dt(x, y, z + k1/2) * del_t
k3 = dz_dt(x, y, z + k2/2) * del_t
k4 = dz_dt(x, y, z + k3) * del_t
return z + (k1 + 2*k2 + 2*k3 + k4)/6
fig = plt.figure()
ax = p3.Axes3D(fig)
#Creating a line object
line, = ax.plot3D([0.0],[10.0],[0.0],'-b')
ax.set_xlim3d(-30,30)
ax.set_xlabel("X")
ax.set_ylim3d(-30,30)
ax.set_ylabel("Y")
ax.set_zlim3d(-30,30)
ax.set_zlabel("Z")
ax.set_title("Lorenz Strange Attractor")
def animate(i, x, y, z, line):
np.append(x, next_xpt(x[i], y[i], z[i]))
np.append(y, next_ypt(x[i], y[i], z[i]))
np.append(z, next_zpt(x[i], y[i], z[i]))
line.set_data(x[:i+1],y[:i+1])
line.set_3d_properties(z[:i+1])
return line
ani = animation.FuncAnimation(fig, animate, fargs = (x, y, z, line), interval=50, blit=False)
答案 0 :(得分:0)
您需要将添加结果保存在数组x
,y
和z
中。您看到它追加的原因是因为您很有可能正在以交互方式对其进行测试。但是正如@hpaulj提到的,出于您的目的,您将必须将附加数组存储在函数中。此外,您必须将x, y, z
声明为global
以反映所做的更改,以避免IndexError
。要初始化线对象,可以定义一个init
函数,然后在您的i
中传递可迭代索引FuncAnimation
docs说(强调我的意思)
返回:append:ndarray
arr的副本,其值附加到axis。请注意,附加操作不会就地发生:已分配并填充了新数组。
您将必须存储新数组
# Initizlise x, y, z here
def init():
line.set_data([], [])
line.set_3d_properties([])
return line,
# dx_dt, dy_dt, dz_dt etc. functions here
fig = plt.figure()
ax = p3.Axes3D(fig)
#Creating a line object
line, = ax.plot3D([0.0],[10.0],[0.0],'-b')
# Setting axes limits here
def animate(i):
global x, y, z
x = np.append(x, next_xpt(x[i], y[i], z[i]))
y = np.append(y, next_ypt(x[i], y[i], z[i]))
z = np.append(z, next_zpt(x[i], y[i], z[i]))
line.set_data(x[:i+1],y[:i+1])
line.set_3d_properties(z[:i+1])
return line,
ani = animation.FuncAnimation(fig, animate, init_func=init, interval=50, blit=False)