python draw parallelepiped

后端 未结 4 770
庸人自扰
庸人自扰 2021-02-08 05:25

I am trying to draw a parallelepiped. Actually I started from the python script drawing a cube as:

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
imp         


        
4条回答
  •  忘掉有多难
    2021-02-08 05:45

    Given that the title of this question is 'python draw 3D cube', this is the article I found when I googled that question.

    For the purpose of those who do the same as me, who simply want to draw a cube, I have created the following function which takes four points of a cube, a corner first, and then the three adjacent points to that corner.

    It then plots the cube.

    The function is below:

    import numpy as np
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D
    from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection
    
    def plot_cube(cube_definition):
        cube_definition_array = [
            np.array(list(item))
            for item in cube_definition
        ]
    
        points = []
        points += cube_definition_array
        vectors = [
            cube_definition_array[1] - cube_definition_array[0],
            cube_definition_array[2] - cube_definition_array[0],
            cube_definition_array[3] - cube_definition_array[0]
        ]
    
        points += [cube_definition_array[0] + vectors[0] + vectors[1]]
        points += [cube_definition_array[0] + vectors[0] + vectors[2]]
        points += [cube_definition_array[0] + vectors[1] + vectors[2]]
        points += [cube_definition_array[0] + vectors[0] + vectors[1] + vectors[2]]
    
        points = np.array(points)
    
        edges = [
            [points[0], points[3], points[5], points[1]],
            [points[1], points[5], points[7], points[4]],
            [points[4], points[2], points[6], points[7]],
            [points[2], points[6], points[3], points[0]],
            [points[0], points[2], points[4], points[1]],
            [points[3], points[6], points[7], points[5]]
        ]
    
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
    
        faces = Poly3DCollection(edges, linewidths=1, edgecolors='k')
        faces.set_facecolor((0,0,1,0.1))
    
        ax.add_collection3d(faces)
    
        # Plot the points themselves to force the scaling of the axes
        ax.scatter(points[:,0], points[:,1], points[:,2], s=0)
    
        ax.set_aspect('equal')
    
    
    cube_definition = [
        (0,0,0), (0,1,0), (1,0,0), (0,0,1)
    ]
    plot_cube(cube_definition)
    

    Giving the result:

提交回复
热议问题