[英]Using matplotlib to generate 3D surfaces from 2D matrices
Using a 2d matrix in python, how can I create a 3d surface plot, where columns=x, rows=y and the values are the heights in z?在 python 中使用 2d 矩阵,如何创建 3d 曲面图,其中列 = x,行 = y,值是 z 中的高度?
I can't understand how to creat 3D surface plot using matplotlib.我无法理解如何使用 matplotlib 创建 3D 曲面图。 Maybe it's different from MatLab.也许它与 MatLab 不同。
example:例子:
from pylab import *
from mpl_toolkits.mplot3d import Axes3D
def p(eps=0.9, lmd=1, err=10e-3, m=60, n=40):
delta_phi = 2 * np.pi / m
delta_lmd = 2 / n
k = 1
P0 = np.zeros([m + 1, n + 1])
P = np.zeros([m + 1, n + 1])
GAP = 1
while GAP >= err:
k = k + 1
for i in range(0, m):
for j in range(0, n):
if (i == 1) or (j == 1) or (i == m + 1) or (i == n + 1):
P[i,j] = 0
else:
A = (1+eps*np.cos((i+1/2)*delta_phi))**3
B = (1+eps*np.cos((i-1/2)*delta_phi))**3
C = (lmd*delta_phi/delta_lmd)**2 * (1+eps*np.cos((i)*delta_phi))**3
D = C
E = A + B + C + D
F = 3*delta_phi*((1+eps*np.cos((i+1/2)*delta_phi))-(1+eps*np.cos((i-1/2)*delta_phi)))
P[i,j] = (A*P[i+1,j] + B*P[i-1,j] + C*P[i,j+1] + D*P[i,j-1] - F)/E
if P[i,j] < 0:
P[i,j] = 0
S = P.sum() - P0.sum()
T = P.sum()
GAP = S / T
P0 = P.copy()
return P, k
def main():
start = time.time()
eps = 0.9
lmd = 1
err = 10e-8
m = 60
n = 40
P, k = p()
fig = figure()
ax = Axes3D(fig)
X = np.linspace(0, 2*np.pi, m+1)
Y = np.linspace(-1, 1, n+1)
X, Y = np.meshgrid(X, Y)
#Z = P[0:m, 0:n]
#Z = Z.reshape(X.shape)
ax.set_xticks([0, np.pi/2, np.pi, np.pi*1.5, 2*np.pi])
ax.set_yticks([-1, -0.5, 0, 0.5, 1])
ax.plot_surface(X, Y, P)
show()
if __name__ == '__main__':
main()
ValueError: shape mismatch: objects cannot be broadcast to a single shape ValueError:形状不匹配:对象不能广播到单个形状
And the pic pic by matplotlic和matplotlic的图片
And I also use MatLab to generate,the pic: pic by MatLab而且我还使用 MatLab 来生成图片:图片来自 MatLab
I should think this is a problem of getting the notaton straight.我应该认为这是一个让符号变直的问题。 A m*n
matrix is a matrix with m
rows and n
columns. m*n
矩阵是具有m
行和n
列的矩阵。 Hence Y
should be of length m
and X
of length n
, such that after meshgridding X
, Y
and P
all have shape (m,n)
.因此Y
的长度应该是m
, X
的长度应该是n
,这样在网格化X
, Y
和P
都具有形状(m,n)
。
At this point there would be no need to reshape of reindex and just plotting在这一点上,不需要重塑 reindex 并只是绘制
ax.plot_surface(X, Y, P)
would give your the desired result.会给你想要的结果。
Let's assume if you have a matrix mat
.让我们假设你有一个矩阵mat
。
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
h, w = mat.shape
plt.figure(figsize=(16, 8))
ax = plt.axes(projection='3d')
X, Y = np.meshgrid(np.arange(w), np.arange(h))
ax.plot_surface(X, Y, mat, rstride=1, cstride=1, cmap='viridis', edgecolor='none', antialiased=False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.