所以,我写了一个简单的代码来使用 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)
繁星淼淼
相关分类