How to plot a 3D grid with a list of xmin, xmax, ymin, ymax, and z values in Python?

Question:

I am just getting into Python and have run into a small problem that I am having trouble solving. I have five lists, each list contains a list of minimum x values, minimum y values, maximum x values, maximum y values and a list of z values.

I am not sure how to turn these lists into a 3D surface plot and would welcome any advice that anyone could give me. I believe that I can use matplotlib for this work, but I am not sure how to implement this. When this is plotted I am expecting it to look something like a Qbert plot with squares at varying height.

The code I have so far is shown below

x_min = [0, 5, 10, 15]
x_max = [5, 10, 15, 20]
y_min = [0, 5, 10, 15] 
y_max = [5, 10, 15, 20]
z = [0, 0, 3, 0, 2]

# Make a 3D Surface Plot
Asked By: jayjay0909

||

Answers:

you should probably familiarize yourself with matplotlib voxels

this is a simple unoptimized example of how to do it based on your input lists.

import matplotlib.pyplot as plt
import numpy as np

x_min_list = [0, 5, 10, 15]
x_max_list = [5, 10, 15, 20]
y_min_list = [0, 5, 10, 15]
y_max_list = [5, 10, 15, 20]
z_list = [0, 0, 3, 0, 2]

fig = plt.figure()
ax = fig.add_subplot(projection='3d')

for xmin,xmax,ymin,ymax,zmax in zip(x_min_list,x_max_list,y_min_list,y_max_list,z_list):

    zmin = zmax-1
    x,y,z = np.indices((2,2,2))
    x = x * (xmax - xmin) + xmin
    y = y * (ymax - ymin) + ymin
    z = z * (zmax - zmin) + zmin

    # and plot everything
    ax.voxels(x,y,z,np.ones((1,1,1)),facecolors='red', edgecolor='k')

ax.set_xlim([min(x_min_list),max(x_max_list)])
ax.set_ylim([min(y_min_list),max(y_max_list)])
ax.set_zlim(min(z_list)-1,max(z_list))
plt.show()

enter image description here

a more optimized approach is to bundle your drawings into 1 ax.voxels call with a very big filtered input array, but you have to have to have the same block size for all your blocks or it may become more complicated, you have to divide the space into blocks and figure out which blocks should be drawn using logical operation, so you will have to give your space some thought … and it may not be faster than the above code.

Answered By: Ahmed AEK
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.