Draw cubes with colour intensity with Python

2.8k views Asked by At

I'd like to know how to plot many cubes with Python. For each cube I have its coordinates (Xmin, Xmax, Ymin, Ymax, Zmin, Zmax) and its value to draw the cube according this value. In fact what I really want to draw voxels.

I've seen some libraries like matplotlib, mayavi, OpenGL, but I don't know which of these libraries to use and how. I think it's not difficult because a cube is an easy regular figure, but I can't reach the solution.

As I have to plot many cubes, it would be good to set the extent, not to represent all the cubes, and I know that mayavi has this option.

2

There are 2 answers

3
aestrivex On

In mayavi, you can use set the glyph type from a list of predefined shapes with mlab.points3d.

points = mlab.points3d(px, py, pz, mode='cube')

This will plot the cube at each point, at the center of the cube.

You can also plot glyphs and then later change the source type with

points.glyph.glyph_source.glyph_source = points.glyph.glyph_source.glyph_dict['cube_source']

(You can also do this in the pipeline menu)

The scale_factor argument will allow you to change the cube size.

It's an inconvenient way to plot voxel by voxel data, but it will do what you asked for.

0
Him On

In mayavi you can plot the faces of a cube with a mesh, for instance.

from mayavi import mlab
import numpy as np

def cube_faces(xmin, xmax, ymin, ymax, zmin, zmax):
    faces = []

    x,y = np.mgrid[xmin:xmax:3j,ymin:ymax:3j]
    z = np.ones(y.shape)*zmin
    faces.append((x,y,z))

    x,y = np.mgrid[xmin:xmax:3j,ymin:ymax:3j]
    z = np.ones(y.shape)*zmax
    faces.append((x,y,z))

    x,z = np.mgrid[xmin:xmax:3j,zmin:zmax:3j]
    y = np.ones(z.shape)*ymin
    faces.append((x,y,z))

    x,z = np.mgrid[xmin:xmax:3j,zmin:zmax:3j]
    y = np.ones(z.shape)*ymax
    faces.append((x,y,z))

    y,z = np.mgrid[ymin:ymax:3j,zmin:zmax:3j]
    x = np.ones(z.shape)*xmin
    faces.append((x,y,z))

    y,z = np.mgrid[ymin:ymax:3j,zmin:zmax:3j]
    x = np.ones(z.shape)*xmax
    faces.append((x,y,z))

    return faces

def mlab_plt_cube(xmin,xmax,ymin,ymax,zmin,zmax):
    faces = cube_faces(xmin,xmax,ymin,ymax,zmin,zmax)
    for grid in faces:
        x,y,z = grid
        mlab.mesh(x,y,z,opacity=0.4)

mlab_plt_cube(0,1,0,1,0,1)
mlab.show()

I'd bet there's a one-liner for the cube_faces function. I'm too tired to contemplate it right this second though.