3D 绘制长方体的所有边

问题描述 投票:0回答:1

我有一个我想要绘制的长方体的坐标(xmin,xmax),(ymin,ymax),(zmin,zmax)(只是所有边)

我该怎么做?

python matplotlib plot shapes matplotlib-3d
1个回答
1
投票

前段时间我从维基百科上抄了一些数学。 此函数为您提供立方体的边和顶点。

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

然后您可以在边缘上循环以在 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='-')

© www.soinside.com 2019 - 2024. All rights reserved.