Home > Back-end >  Matplotlib 3D plotting all the edges of a cuboid
Matplotlib 3D plotting all the edges of a cuboid

Time:09-02

I have the coordinates (xmin,xmax), (ymin,ymax), (zmin, zmax) of a cuboid which I want to be plotted (just all the edges)

How can I do that?

CodePudding user response:

I copied some math from Wikipedia some while ago. This function gives you, the edges and vertices of a cube.

import numpy as np


def get_cube(limits=None):
    """get the vertices, edges, and faces of a cuboid defined by its limits

    limits = np.array([[x_min, x_max],
                       [y_min, y_max],
                       [z_min, z_max]])
    """
    v = np.array([[0, 0, 0], [0, 0, 1],
                  [0, 1, 0], [0, 1, 1],
                  [1, 0, 0], [1, 0, 1],
                  [1, 1, 0], [1, 1, 1]], dtype=int)

    if limits is not None:
        v = limits[np.arange(3)[np.newaxis, :].repeat(8, axis=0), v]

    e = np.array([[0, 1], [0, 2], [0, 4],
                  [1, 3], [1, 5],
                  [2, 3], [2, 6],
                  [3, 7],
                  [4, 5], [4, 6],
                  [5, 7],
                  [6, 7]], dtype=int)

    f = np.array([[0, 2, 3, 1],
                  [0, 4, 5, 1],
                  [0, 4, 6, 2],
                  [1, 5, 7, 3],
                  [2, 6, 7, 3],
                  [4, 6, 7, 5]], dtype=int)

    return v, e, f

Then you can just loop over the edges to draw the cube in matplotlib.

limits = np.array([[-2, 1],
                   [-1, 1],
                   [0, 2]])

v, e, f = get_cube(limits)

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(*v.T, marker='o', color='k', ls='')
for i, j in e:
    ax.plot(*v[[i, j], :].T, color='r', ls='-')

3d cuboid

  • Related