用Python绘制表面

时间:2018-12-11 16:51:10

标签: python matplotlib plot surface

我正在尝试绘制一些数据,该数据由4个变量组成。我正在使用2种方法,一种是散点图,另一种是曲面。问题是当我使用曲面时,数据丢失了。我认为这与颜色设置有关。

对于散点图,我使用它:

def scatter3d(x,y,z, cs, colorsMap='jet'):
   cm = plt.get_cmap(colorsMap)
   cNorm = matplotlib.colors.Normalize(vmin=min(cs), vmax=max(cs))
   scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)
   fig = plt.figure()
   ax = Axes3D(fig)
   ax.scatter(x, y, z,c=scalarMap.to_rgba(cs))
   ax.set_xlabel('Thita1')
   ax.set_ylabel('Thita2')
   ax.set_zlabel('Fairness (%)')
   scalarMap.set_array(cs)
   fig.colorbar(scalarMap,label='Error Rate (%)')
   plt.show()

enter image description here

我想使用以下方法将其转换为表面图:

   def surfacePlot(x,y,z, cs, colorsMap='jet'):
    cm = plt.get_cmap(colorsMap)
    cNorm = matplotlib.colors.Normalize(vmin=min(cs), vmax=max(cs))
    scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.plot_surface(x, y, z, facecolors=scalarMap.to_rgba(cs))
    ax.set_xlabel('Thita1')
    ax.set_ylabel('Thita2')
    ax.set_zlabel('Fairness')
    scalarMap.set_array(cs)
    fig.colorbar(scalarMap,label='Error Rate (%)')
    plt.show()

但是,这将导致一个空网格:

enter image description here

尽管轴已经从矢量接收到了最小值和最大值,但是这些点仍然缺失。我在做什么错了?

1 个答案:

答案 0 :(得分:-1)

如前所述,plot_surface需要二维数组数据或网格-类似于您熟悉的热图创建方法。如果您的数据在x,y轴上有规律的间隔(看起来确实如此),则可以简单地使用格式化为2d数组的z数据,如注释中链接的先前示例所示:

grid_x, grid_y = np.meshgrid(x, y)

# I'm assuming that your data is already mesh-like, which it looks like it is.
# The data would also need to be appropriately sorted for `reshape` to work.
# `dx` here is number of unique x values, and `dy` is number unique y values.
grid_z = z.reshape(dy, dx)

ax.plot_scatter(grid_x, grid_y, grid_z)

但是,通常在x,y,z点间距不均匀的情况下,可以对数据进行插值以创建网格。 Scipy具有函数griddata,该函数将插值到已定义的网格上。您可以使用它来绘制数据:

from scipy.interpolate import griddata
xy = np.column_stack([x, y])
grid_x, grid_y = np.mgrid[0:1:100j, 0:1:100j]  # grid you create
grid_z = griddata(xy, z, (grid_x, grid_y))
ax.plot_scatter(grid_x, grid_y, grid_z)