Home > database >  Matplotlib - Plotting 3D cubes of same size given center coordinates
Matplotlib - Plotting 3D cubes of same size given center coordinates

Time:06-06

I have a spatial dataset with the center coordinates of cubes with a specific size (20 m), and a variable for color mapping.

I want to plot these cubes in 3D; however, I couldn't find a way to do it. I've tried to implement a voxel code by calculating the corner coordinates of the cubes but got stuck after some point.

The dataset looks like this:

      x       y      z     variable
0   14630   21750   4690    0.087
1   14630   21770   4690    0.046
2   14630   21790   4690    0.045
3   14630   21930   5290    0.1657
4   14630   21950   5270    0.1144

I'm not sure if I should be using ax.voxels or Poly3DCollection. So, if you have any tips, I'd appreciate it.

CodePudding user response:

IIUC, simply modifying enter image description here

Code to plot 3D cubes:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd

df = pd.DataFrame({"x": [14630, 14630, 14360, 14360, 14360], "y" : [21750, 21770, 21790, 21930, 21950], "z" : [4690, 4690, 4690, 5290, 5270]})

def get_cube():   
    phi = np.arange(1,10,2)*np.pi/4
    Phi, Theta = np.meshgrid(phi, phi) 

    x = np.cos(Phi)*np.sin(Theta)
    y = np.sin(Phi)*np.sin(Theta)
    z = np.cos(Theta)/np.sqrt(2)
    return x,y,z


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
L = 20

for i in df.index:
    x,y,z = get_cube()
    
    # Change the centroid of the cube from zero to values in data frame
    x = x*L   df.x[i]
    y = y*L   df.y[i]
    z = z*L   df.z[i]
    ax.plot_surface(x, y, z)
    ax.set_zlabel("z")

plt.xlabel("x")
plt.ylabel("y")
plt.show()
  • Related