在 Python 中绘制曲面

Draw surface in Python

我有想要绘制的规则网格。我用了plot_surface,结果有点奇怪。你能帮忙画画吗?我试图更改轴的限制,但没有帮助。也许您可以建议将点绘制为曲面的更好方法。谢谢!

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
from array import *

x = np.array([0, 0, 0, 400, 400, 400, 800, 800, 800])
y = np.array([0, 400, 800, 0, 400, 800, 0, 400, 800])
z = np.array([10.0, 10.0, 10.0, 10.0, 206.8, 10.0, 10.0, 10.0, 10.0])

#print len(x), len(y), len(z)

zdict = {}

for i in range (0, len(x)):
    #print "(", x[i], ", ", y[i], "): ", z[i], ", "
    zdict[(x[i], y[i])] = z[i]

print zdict

def zfunc(x, y):
    return zdict[(x, y)]

X, Y = np.meshgrid(x, y)

print X, Y

#need 2d array of Z

Z = [[zfunc(X[i][j], Y[i][j]) for i in range(0, len(X))] for j in range(0,    len(X[0]))]

print Z

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)
ax.set_zlim(0, 300.0)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()

您的网格是错误的:它包含许多重复的 xy 值。试试这个:

In [7]: X,Y = meshgrid(unique(x), unique(y))

In [8]: X
Out[8]: 
array([[  0, 400, 800],
       [  0, 400, 800],
       [  0, 400, 800]])

In [9]: Y
Out[9]: 
array([[  0,   0,   0],
       [400, 400, 400],
       [800, 800, 800]])

In [10]: Z = z.reshape((3,3))

In [11]: fig = plt.figure()
    ...: ax = fig.gca(projection='3d')
    ...: surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0)