希望有人能帮助我。我的目标是制作一个函数U(x,z,t)的动画,特别是三维函数U(x,z)的时间演化。 首先,我编写了一些代码,对时间步进进行离散化,并将每个“快照”保存在数组U[t]中,其中t是{0,1,…,Nt}中的整数,时间步数为Nt。U[0]是初始函数,并已给出。 我想指出,U[t](t in{0,1,…,Nt})都是包含数字的矩阵,并且已经适合于绘制。 现在,我想设置一个绘图的动画,以便:
我的第一个方法是只使用“for cycle”。不幸的是,我没有创建一个刷新的图像,而是创建了一系列不同的图形。 代码是:
for i in range(0,Nt+1):
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_surface(gridx, gridz, U[i],cmap='viridis', edgecolor='none')
#gridx,gridz are created via np.meshgrid(...)
ax.set_title("Function U at time-step " + str(i)+ ". Time "+ str(i*dt)+ "." )
ax.set_xlabel('X')
ax.set_ylabel('Z')
ax.set_zlabel('u(x,z)')
plt.show()
现在我试着在网上搜索,发现很多不同的例子使用matplotlib.animation和FuncAnimation或者仅仅使用animation。问题是我不知道如何使这些例子适应我的案例。 有人能帮我解决这个问题吗
更新:对于函数也可以是变量的情况,我编写了以下代码:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation
def Animate(gridx,gridz,Nt,Name, func,dt):
fig = plt.figure()
ax = fig.gca(projection= "3d")
ax.set_xlabel('X')
ax.set_ylabel('Z')
ax.set_zlabel(Name)
def update(frame,fig):
if len(fig.axes[0].collections) != 0:
fig.axes[0].collections = []
surf = fig.axes[0].plot_surface(gridx, gridz, func[frame], cmap= "viridis")
ax.set_title("Function "+ Name + " at time-step " + str(frame)+ ". Time "+ str(frame*dt)+ ".", y = 1 )
else:
surf = fig.axes[0].plot_surface(gridx, gridz, func[frame], cmap= "viridis")
ax.set_title("Function " + Name + " at time-step " + str(frame)+ ". Time "+ str(frame*dt)+ "." )
fig.canvas.draw()
return surf,
ani =FuncAnimation(fig,update,fargs=[fig],frames = Nt+1, blit = True)
ani.save("Gif for the function " + Name + ".gif")
return
可以使用不同的函数调用此代码,以便在需要可视化更多函数时简化处理
我使用下面的代码通过向曲面添加随机z方向位移来制作动画,希望它能解决您的问题。请仔细阅读animation tutorial和3d线条示例3D animation lines。当我重新绘制曲面时,我的解决方案可能并不有效,但它应该很容易理解
相关问题 更多 >
编程相关推荐