Search code examples
pythonmatplotlibcolorbarheightmapmatplotlib-3d

Plot 3d points (x,y,z) in 2d plot with colorbar


I have computed a lot (~5000) of 3d points (x,y,z) in a quite complicated way so I have no function such that z = f(x,y). I can plot the 3d surface using

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
X = surface_points[:,0]
Y = surface_points[:,1]
Z = surface_points[:,2]
fig = plt.figure()
ax = fig.add_subplot(projection='3d') 
surf = ax.plot_trisurf(X, Y, Z, cmap=cm.coolwarm, vmin=np.nanmin(Z), vmax=np.nanmax(Z))

I would like to plot this also in 2d, with a colorbar indicating the z-value. I know there is a simple solution using ax.contour if my z is a matrix, but here I only have a vector.

Attaching the plot_trisurf result when rotated to xy-plane. This is what I what like to achieve without having to rotate a 3d plot. In this, my variable surface_points is an np.array with size 5024 x 3.

enter image description here


Solution

  • I had the same problems in one of my codes, I solved it this way:

    import numpy as np
    from scipy.interpolate import griddata
    import matplotlib.pylab as plt
    from matplotlib import cm
    
    N = 10000
    surface_points = np.random.rand(N,3)
    X = surface_points[:,0]
    Y = surface_points[:,1]
    Z = surface_points[:,2]
    
    nx = 10*int(np.sqrt(N))
    xg = np.linspace(X.min(), X.max(), nx)
    yg = np.linspace(Y.min(), Y.max(), nx)
    xgrid, ygrid = np.meshgrid(xg, yg)
    ctr_f = griddata((X, Y), Z, (xgrid, ygrid), method='linear')
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1) 
    ax.contourf(xgrid, ygrid, ctr_f, cmap=cm.coolwarm)
    
    plt.show()
    

    enter image description here