【问题标题】:3D surface with matplotlib is incorrect but contour plot is correct使用 matplotlib 的 3D 表面不正确,但等高线图正确
【发布时间】:2021-05-20 22:46:00
【问题描述】:

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

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

请看我下面的代码:

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)

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

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

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

    请注意,我使用的是xvyv 而不是XY

    这是我的输出。

    【讨论】:

    • 哦,我现在明白了。感谢您的回答!
    • 没问题 :) 这些东西总是漏掉
    猜你喜欢
    • 2022-08-19
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    相关资源
    最近更新 更多