在Python中使用matplotlib设置与时间相关的3Dfunction动画

2024-10-04 07:32:15 发布

您现在位置:Python中文网/ 问答频道 /正文

希望有人能帮助我。我的目标是制作一个函数U(x,z,t)的动画,特别是三维函数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)直到timestep 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

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

结果是: Example of Gif for a function P


Tags: 函数代码namefordtfigpltax
1条回答
网友
1楼 · 发布于 2024-10-04 07:32:15

我使用下面的代码通过向曲面添加随机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)

相关问题 更多 >