0

希望可以有人帮帮我。我的目标是为函数 U(x,z,t) 制作动画,特别是 3D 函数 U(x,z) 的时间演化。首先,我编写了一些离散时间步长的代码,并将每个“快照”保存在数组 U[t] 中,其中 t 是 {0,1,...,Nt} 中的整数,用于 Nt 个时间步长。U[0] 是初始函数并给出。我想指出 U[t] (t in {0,1,...,Nt} 都是包含数字的矩阵,并且已经适合绘制。我现在想要为绘图设置动画,以便:

  1. 窗口中显示的第一幅图像是 U[0],即带有适当标签的初始函数。
  2. 然后窗口刷新并显示带有适当标签的U 1 。
  3. 然后它重复步骤 (2) 直到时间步长 Nt。

我的第一种方法是仅使用“for 循环”。不幸的是,我没有创建一个令人耳目一新的图像,而是创建了一系列不同的图形。代码是:

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

可以使用不同的函数调用此代码,以方便您在需要可视化更多函数时进行处理。

结果是: 函数 P 的 Gif 示例

4

1 回答 1

0

我使用以下代码通过向表面添加随机 z 方向位移来制作动画,希望它可以解决您的问题。请仔细阅读动画教程,以及 3d 线条示例3D 动画线条。当我重绘表面时,我的解决方案可能不是有效的,但它应该很容易理解。

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D  



fig = plt.figure()
ax = fig.gca(projection='3d')


def update(frame, fig):
    X = np.arange(-5, 5, 0.25)
    Y = np.arange(-5, 5, 0.25)
    X, Y = np.meshgrid(X, Y)
    R = np.sqrt(X**2 + Y**2)
    # add random shift in z directions
    Z = np.sin(R)+np.random.random_sample()
    if len(fig.axes[0].collections) != 0:
        fig.axes[0].collections = []
        surf = fig.axes[0].plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)
    else:
        surf = fig.axes[0].plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)
    ax.set_zlim(-1.5, 1.5)

    fig.canvas.draw()
    return surf,
    
ani = FuncAnimation(fig, update, fargs=[fig], frames=5, blit=True)
于 2020-09-30T12:37:42.223 回答