首页 > 解决方案 > 使用 matplotlib 的 3D 表面不正确,但等高线图正确

问题描述

我正在尝试使用 matplotlib 为一堆数学函数绘制 3D 曲面。这些函数被定义为以任意长度的一维 numpy 数组作为输入。

当绘制为等高线图时,该图看起来是正确的。. 但是,3D 曲面图显示了一个已被压扁到一条线上的曲面。我使用相同的值进行绘图,所以它们应该是相同的,但这不是我得到的,我对此感到非常困惑

请在下面查看我的代码:

from mpl_toolkits.mplot3d import Axes3D

# build the meshgrid
x = np.linspace(bounds[0][0],bounds[0][1])
y = np.linspace(bounds[1][0], bounds[1][1])
xv, yv = np.meshgrid(x, y)

# populate z
z = np.zeros_like(xv)
for row_idx in range(xv.shape[0]):
    for col_idx in range(xv.shape[1]):
        z[row_idx][col_idx] = function(np.array([xv[row_idx][col_idx], yv[row_idx][col_idx]]))

# plot 3D surface
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_surface(x, y, z, cmap='viridis', edgecolor='none')

# plot a contour
ax.contourf(x, y, z, cmap='viridis')
plt.show()

# function that I'm plotting -> bowl shaped for 2D x
def function(x):
    return sum(x**2)

标签: pythonmatplotlib

解决方案


我可能有这个错误,但如果你只是想要表面网格,你需要绘制网格数据而不是线性数据,所以只需更改这条线:

ax.plot_surface(xv, yv, z, cmap='viridis', edgecolor='none')

请注意,我使用的是xv,yv而不是X, Y

这是我的输出。在此处输入图像描述


推荐阅读