使用线条/条连接3D点

时间:2014-09-04 13:27:27

标签: python matplotlib 3d points connection

我目前在3D空间中绘制了一系列点。我想将它们连接在一起形成一个矩形。矩形需要一定的宽度和高度,并且如果遇到框边界,应该以某种方式“包裹”到gthe框的另一边。

我的代码如下:

import matplotlib.pyplot as pyplot
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

x       = [0, 0, 0, 0, 50, 50, 50, 50]
y       = [50,50,50,50,50,50,50,50]
z       = [12.5,37.5,62.5,87.5,25,50,75,0]

fig = pyplot.figure()
ax  = fig.add_subplot(111, projection = '3d')

ax.set_xlim(0,100)
ax.set_ylim(0,100)
ax.set_zlim(0,100)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

#ax.view_init(elev=90, azim=90)
ax.scatter(x, y, z, zdir='z', s=20, c='g')

pyplot.show()

有人有什么想法吗?非常感谢

1 个答案:

答案 0 :(得分:0)

一种可能的算法是

  1. 找到矩形的顶点
  2. 重新排序顶点以形成rectagle
  3. 这是一个可能的解决方案:

    #!/usr/bin/env python3
    
    import matplotlib.pyplot as pyplot
    from numpy import *
    from numpy import linalg
    from mpl_toolkits.mplot3d import Axes3D
    
    x       = array([0, 0, 0, 0, 50, 50, 50, 50])
    y       = array([50,50,50,50,50,50,50,50])
    z       = array([12.5,37.5,62.5,87.5,25,50,75,0])
    
    data = concatenate((x[:,newaxis],y[:,newaxis],z[:,newaxis]), axis=1)
    
    center = data.mean(axis=0)
    
    distances = empty((0))
    for row in data:
        distances = append(distances, linalg.norm(row - center))
    
    vertices = distances.argsort()[-4:]
    Vertices_reorder = [vertices[0], vertices[2], vertices[1], vertices[3], vertices[0]]
    
    # plot:
    fig = pyplot.figure()
    ax  = fig.add_subplot(111, projection = '3d')
    
    ax.set_xlim(0,100)
    ax.set_ylim(0,100)
    ax.set_zlim(0,100)
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')
    
    #ax.view_init(elev=90, azim=90)
    ax.scatter(x, y, z, zdir='z', s=20, c='g')
    ax.plot(x[Vertices_reorder], y[Vertices_reorder], z[Vertices_reorder])
    
    fig.savefig("rect.png")
    

    结果:

    enter image description here

    我不确定实施的重新排序是否适用于所有情况。