【问题标题】:Animate time-dependent 3D-function using matplotlib in Python在 Python 中使用 matplotlib 对时间相关的 3D 函数进行动画处理
【发布时间】:2020-09-30 09:08:15
【问题描述】:

希望有人可以帮助我。我的目标是为函数 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. 然后窗口刷新并显示带有适当标签的 U1
  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

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

结果是: Example of Gif for a function P

【问题讨论】:

    标签: python matplotlib matplotlib-animation


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 成功了!真的非常感谢!我还为轴添加了标题。我想知道是否可以将更新函数概括为:``` def update(frame,fig,func) ``` 这样我就可以输入一个通用函数来绘制。
    • 为什么需要在更新中传递函数调用?不确定这是否有效,您可以根据我的代码尝试,并相应地更新fargs
    • 其实你是对的......我决定创建一个新函数来处理这个问题。我会把它添加到我原来的帖子中。
    • 您强烈建议您先自己尝试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 2016-10-08
    • 1970-01-01
    相关资源
    最近更新 更多