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

Time:05-06

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

CodePudding user response:

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

CodePudding user response:

You could use a scatter plot to display a projection of your z color onto the x-y axis.

import numpy as np
import matplotlib.pyplot 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]
# 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))

fig = plt.figure()

cmap = cm.get_cmap('coolwarm')
color = cmap(Z)[..., :3]

plt.scatter(X,Y,c=color)

plt.show()

enter image description here

Since you seem to have a 3D shape that is hollow, you could split the projection into two like if you cur the shape in two pieces.

fig = plt.figure()
plt.subplot(121)
plt.scatter(X[Z<0.5],Y[Z<0.5],c=color[Z<0.5])
plt.title('down part')
plt.subplot(122)
plt.scatter(X[Z>=0.5],Y[Z>=0.5],c=color[Z> 0.5])
plt.title('top part')
plt.show()

enter image description here

  • Related