从中心绘制3D立方体

时间:2014-07-03 05:30:05

标签: python python-2.7 matplotlib 3d

如果提供了中心坐标,我想绘制尺寸为1.0的3D立方体并返回坐标字典。

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#Concept.py    

def printer(Coordinates):
    A = B = C = 1.0
    X,Y,Z = Coordinates
    S = 1.0
    Q = 1.0
    O2 = [X,Y,Z]
    O1 = [X, Y - S, Z]
    O3 = [X, Y + S, Z]
    A1 = [X - Q, Y - Q, Z - Q]
    B1 = [X + Q, Y - Q, Z - Q]
    C1 = [X + Q, Y - Q, Z + Q]
    D1 = [X - Q, Y - Q, Z + Q]
    E1 = [X,     Y - Q, Z - Q]
    F1 = [X + Q, Y - Q, Z]
    G1 = [X,     Y - Q, Z + Q]
    H1 = [X - Q, Y - Q, Z]
    A2 = [X - S, Y, Z - S]
    B2 = [X + S, Y, Z - S]
    C2 = [X + S, Y, Z + S]
    D2 = [X - S, Y, Z + S]
    E2 = [X,         Y,   Z - S]
    F2 = [X + S,     Y,   Z]
    G2 = [X,         Y,   Z + S]
    H2 = [X - S,     Y,   Z]
    A3 = [X - Q ,Y + Q, Z - Q]
    B3 = [X + Q ,Y + Q, Z - Q]
    C3 = [X + Q ,Y + Q, Z + Q]
    D3 = [X - Q ,Y + Q, Z + Q]
    E3 = [X,     Y + Q, Z - Q]
    F3 = [X + Q, Y + Q, Z]
    G3 = [X,     Y + Q, Z + Q]
    H3 = [X - Q, Y + Q, Z]
#    print A1, B1, C1, D1, E1, 
#    print F1, G1, H1, O1, A2, 
#    print B2, C2, D2, E2, F2, 
#    print G2, H2,A3, B3, C3, 
#    print D3, E3, F3, G3, H3, O3
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    h = [A1, B1, C1, D1, E1, F1, G1, H1, O1, 
        A2, B2, C2, D2, E2, F2, G2, H2,
        A3, B3, C3, D3, E3, F3, G3, H3, O3]
    hx, hy, hz = zip(*h)
    ax.plot(hx,hy,hz, "o-")
    hold = {"A1": A1,  "B1": B1,  "C1": C1,  "D1": D1,
            "E1": E1,  "F1": F1,  "G1": G1,  "H1": H1,
            "O1": O1,  "A2": A2,  "B2": B2,  "C2": C2,
            "D2": D2,  "E2": E2,  "F2": F2,  "G2": G2,
            "H2": H2,  "A3": A3,  "B3": B3,  "C3": C3,
            "D3": D3,  "E3": E3,  "F3": F3,  "G3": G3,
            "H3": H3,  "O3": O3}
    plt.show()
    return {i:eval(i) for i in hold}

printer([0,0,0])

我希望结果如下:

enter image description here

问题: 1.)它返回错误:

Traceback (most recent call last):
  File "concept.py", line 59, in <module>
    printer([0,0,0])
  File "concept.py", line 57, in printer
    return {i:eval(i) for i in hold}
  File "concept.py", line 57, in <dictcomp>
    return {i:eval(i) for i in hold}
  File "<string>", line 1, in <module>
NameError: name 'O3' is not defined

2。)虽然情节显示:     enter image description here

PS:我知道Python/matplotlib : plotting a 3d cube, a sphere and a vector?。但我不知道如何从那里获取坐标或定义我的中心。

1 个答案:

答案 0 :(得分:2)

您应该使用算法方法而不是硬编码。更紧凑(可能)和更少的错误。可能最好将点定义为线的起点,中心点和终点,而不是定义点然后定义线。逆时针方向从上往下看,模式只是[&#34; A&#34;,&#34; E&#34;,&#34; B&#34;,&#34; F&#34;,&#34 ; C&#34;&#34; G&#34;&#34; d&#34;&#34; H&#34;&#34; A&#34]。因此,水平线是AEB(1-3),BFC(1-3),CGD(1-3)和DHA(1-3)。