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?
I copied some math from wikipedia some while ago.
This function gives you the edges and vertices of a cube.
How the edges and faces are connected is hardcoded, also the ordering is fixed and starts from the lower left corner of the cube,
With the limits
argument you can specify where the cube is located.
It is always axes-aligned.
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='-')