绘制曲面而不是参数曲线

时间:2016-05-05 18:04:16

标签: python matplotlib plot pde numerics

我正在努力使用前向差分方案在一维中数值求解扩散函数。我对解决方案的最终绘图应该是一个表面,其中解x(x,t)被绘制在x和t值的网格上。我已经解决了问题,但我无法使用网格表示来绘制数据。

我可以想出两种方法来解决这个问题:

1。)我的x和t数组应该是一维的,但是我的u数组应该是2D数组。最终,我想要一个方形矩阵,但我很难编码。目前我有一个1D数组给你。这是填充u的代码。

u   = zeros(Nx+1)           # unknown u at new time level
u_1 = zeros(Nx+1)           # u at the previous time level
# Set initial condition u(x,0) = I(x)
for i in range(0, Nx+1):
#set initial u's to I(xi)
    u_1[i] = 25-x[i]**2
for n in range(0, Nt):
# Compute u at inner mesh points
    for i in range(1, Nx):
        u[i] = u_1[i] + F*(u_1[i-1] - 2*u_1[i] + u_1[i+1])

2。)上面的代码为你返回一个1D数组,有没有办法用x,y,z三个1D数组绘制一个3D表面?

1 个答案:

答案 0 :(得分:0)

嗯......,您还没有提供很多信息。例如,你说你想要一个x,y,z图,但是没有说明你的情节中x,y和z应该是什么。 z通常也是z(x,y)。

以下方法假设tx以及u(t,x)作为要放入曲面的变量。我想象的并不完全是你的想法,但它应该适合你的运动:

编辑:此外,您的代码(在此配方中的函数computeU中)有一个Nt的循环似乎什么也没做。为了这个例子,我已将其删除了。

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

def computeU(Nx,x,F,Nt):
    u   = np.zeros(Nx+1)           # unknown u at new time level
    u_1 = np.zeros(Nx+1)           # u at the previous time level
    # Set initial condition u(x,0) = I(x)
    for i in range(0, Nx+1):
    #set initial u's to I(xi)
        u_1[i] = 25-x[i]**2
    #for n in range(0, Nt): # I'm not sure what this is doing. It has no effect.
    # Compute u at inner mesh points
    for i in range(1, Nx):
        u[i] = u_1[i] + F*(u_1[i-1] - 2*u_1[i] + u_1[i+1])
    return np.hstack((u[:,np.newaxis],u_1[:,np.newaxis]))

Nx = 10
F  = 3
Nt = 5
x  = np.arange(11)
t  = np.arange(2)

X,Y = np.meshgrid(t,x)
Z = computeU(Nx,x,F,Nt)
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,linewidth=0, antialiased=False)
plt.show()

注意我是如何使用meshgrid构建新tx(来自1D数组)映射到U数组的堆栈(其中将具有XY的相同形状 - 新tx)。结果如下:

Surface built from several 1D arrays