在Python 3.0上通过“t”变量动画制作3D方程式/绘图

时间:2017-11-05 22:10:59

标签: python animation matplotlib 3d

我的目标是通过“告诉”Python增加所述等式中存在的“t”变量来动画超特定(规范)扩散方程。我在Mathematica中轻松完成了这项工作,但需要将Python用于我指定的研究项目。 该等式被结构化/定义为c(x,y,t),显然我的问题适用于c(x,y,t)设置为相等的任何类型的函数。每个答案都与我的问题有关:

  

1)不包括不是PDE的功能

     

2)包括不递增时间变量(t)

此外,我找不到任何方法来绘制Python上用于2个变量的3D方程。

编辑:我已经想出办法来做到这一点。

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

def fun(x, t):
  return x+t #Any equation
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.arange(-20.0, 20.0, 0.05)
t = np.arange(0.0,50.0,1)
X, Y = np.meshgrid(x, t)
zs = np.array([fun(x,t) for x,t in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)

ax.plot_surface(X, Y, Z)

ax.set_xlabel('X Position')
ax.set_ylabel('Time')
ax.set_zlabel('Concentration')

plt.show()

信用:Wim I want to use matplotlib to make a 3d plot given a z function

动画程序的任何帮助或简单代码都意味着很多,因为我的研究项目涉及7D数学,这本质上是我试图做的非平凡表示的最基本的例子。所以期待更多的问题(无论答案如何)。

1 个答案:

答案 0 :(得分:0)

好的,让我们以this answer为例。我们可以轻松地修改它以使用函数c(x,y,t)而不是f(x,y,sig)(这些只是变量名)。

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

def update_plot(frame_number, zarray, plot):
    plot[0].remove()
    plot[0] = ax.plot_surface(x, y, zarray[:,:,frame_number], cmap="magma")

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

N = 14
nmax=20
x = np.linspace(-4,4,N+1)
x, y = np.meshgrid(x, x)
zarray = np.zeros((N+1, N+1, nmax))

sig = lambda t: 1.5+np.sin(t*2*np.pi/nmax)
c = lambda x,y,t : 1/np.sqrt(sig(t))*np.exp(-(x**2+y**2)/sig(t)**2)

for t in range(nmax):
    zarray[:,:,t] = c(x,y,t)

plot = [ax.plot_surface(x, y, zarray[:,:,0], color='0.75', rstride=1, cstride=1)]
ax.set_zlim(0,1.5)
animate = animation.FuncAnimation(fig, update_plot, nmax, fargs=(zarray, plot))
plt.show()

enter image description here