【问题标题】:Python Matplotlib - Plotting cuboidsPython Matplotlib - 绘制长方体
【发布时间】:2018-08-22 23:35:48
【问题描述】:

我正在尝试使用 matplotlib 绘制不同大小的长方体,这样:旋转后长方体不会以非物理方式在视觉上重叠,立方体具有不同的颜色,并且在它们周围绘制了一个框。

我已经阅读了几篇博客文章和 stackoverflow 页面引用了类似的问题,但总是略有不同;没有一个对我有用。克服重叠问题的最简单方法是使用体素(如https://matplotlib.org/api/_as_gen/mpl_toolkits.mplot3d.axes3d.Axes3D.html?highlight=voxel#mpl_toolkits.mplot3d.axes3d.Axes3D.voxels),但这些不允许我在它们周围绘制框。在 matplotlib 中最简单的方法是什么?

下图左边是我拥有的,右边是我想要的。

编辑: 我研究了几种可以产生预期效果的方法,其中主要的有:

  • 使用体素,但以某种方式对其进行缩放,使得单个体素代表单个项目。
  • 使用曲面图,但随后动态调整绘图顺序以避免非物理重叠。

前者似乎更容易执行,但我仍然很难过。

【问题讨论】:

  • 那么你面临的问题是体素的尺寸总是1x1x1?
  • 我已经想到了几种解决问题的方法,事实上,如果可以调整它,那将是一个可能的解决方案。此外,它是一种有望增加可扩展性的解决方案;我希望能够将此可视化应用于边界域通常为 [0,0,0]x[1000,1000,1000] 的数据集,并且不必显式存储每个单元格将大大减少内存使用量。我想展示的大约 40 个框几乎从不小于 10x10x10。任何其他实现这种可视化的方法(在 matplotlib 中)也很好(不仅仅是通过体素)。

标签: python matplotlib 3d voxels


【解决方案1】:

A.使用Poly3DCollection

一个选项是创建一个长方体面的Poly3DCollection。由于同一收藏的艺术家不存在重叠问题,这可能最适合这里的目的。

from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import numpy as np
import matplotlib.pyplot as plt

def cuboid_data2(o, size=(1,1,1)):
    X = [[[0, 1, 0], [0, 0, 0], [1, 0, 0], [1, 1, 0]],
         [[0, 0, 0], [0, 0, 1], [1, 0, 1], [1, 0, 0]],
         [[1, 0, 1], [1, 0, 0], [1, 1, 0], [1, 1, 1]],
         [[0, 0, 1], [0, 0, 0], [0, 1, 0], [0, 1, 1]],
         [[0, 1, 0], [0, 1, 1], [1, 1, 1], [1, 1, 0]],
         [[0, 1, 1], [0, 0, 1], [1, 0, 1], [1, 1, 1]]]
    X = np.array(X).astype(float)
    for i in range(3):
        X[:,:,i] *= size[i]
    X += np.array(o)
    return X

def plotCubeAt2(positions,sizes=None,colors=None, **kwargs):
    if not isinstance(colors,(list,np.ndarray)): colors=["C0"]*len(positions)
    if not isinstance(sizes,(list,np.ndarray)): sizes=[(1,1,1)]*len(positions)
    g = []
    for p,s,c in zip(positions,sizes,colors):
        g.append( cuboid_data2(p, size=s) )
    return Poly3DCollection(np.concatenate(g),  
                            facecolors=np.repeat(colors,6), **kwargs)
    

positions = [(-3,5,-2),(1,7,1)]
sizes = [(4,5,3), (3,3,7)]
colors = ["crimson","limegreen"]

fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect('equal')

pc = plotCubeAt2(positions,sizes,colors=colors, edgecolor="k")
ax.add_collection3d(pc)    

ax.set_xlim([-4,6])
ax.set_ylim([4,13])
ax.set_zlim([-3,9])

plt.show()

B.使用plot_surface

从使用plot_surfacethis question 调整解决方案,并允许此处所需的不同尺寸在大多数情况下似乎都可以正常工作:

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

def cuboid_data(o, size=(1,1,1)):
    # code taken from
    # https://stackoverflow.com/a/35978146/4124317
    # suppose axis direction: x: to left; y: to inside; z: to upper
    # get the length, width, and height
    l, w, h = size
    x = [[o[0], o[0] + l, o[0] + l, o[0], o[0]],  
         [o[0], o[0] + l, o[0] + l, o[0], o[0]],  
         [o[0], o[0] + l, o[0] + l, o[0], o[0]],  
         [o[0], o[0] + l, o[0] + l, o[0], o[0]]]  
    y = [[o[1], o[1], o[1] + w, o[1] + w, o[1]],  
         [o[1], o[1], o[1] + w, o[1] + w, o[1]],  
         [o[1], o[1], o[1], o[1], o[1]],          
         [o[1] + w, o[1] + w, o[1] + w, o[1] + w, o[1] + w]]   
    z = [[o[2], o[2], o[2], o[2], o[2]],                       
         [o[2] + h, o[2] + h, o[2] + h, o[2] + h, o[2] + h],   
         [o[2], o[2], o[2] + h, o[2] + h, o[2]],               
         [o[2], o[2], o[2] + h, o[2] + h, o[2]]]               
    return np.array(x), np.array(y), np.array(z)

def plotCubeAt(pos=(0,0,0), size=(1,1,1), ax=None,**kwargs):
    # Plotting a cube element at position pos
    if ax !=None:
        X, Y, Z = cuboid_data( pos, size )
        ax.plot_surface(X, Y, Z, rstride=1, cstride=1, **kwargs)

positions = [(-3,5,-2),(1,7,1)]
sizes = [(4,5,3), (3,3,7)]
colors = ["crimson","limegreen"]


fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect('equal')

for p,s,c in zip(positions,sizes,colors):
    plotCubeAt(pos=p, size=s, ax=ax, color=c)

plt.show()

【讨论】:

  • 对于这段代码,我提到的不自然重叠发生在某些方向上。
  • 那是哪个方向?
  • 使用 Matplotlib 2.2.0 版,我得到以下行为:imgur.com/a/PME5J
  • 我最终只是使用了不同的库。 VPython 运行良好且易于安装。
  • 注意: ax.set_aspect('equal')not supported anymore ,请改用 ax.set_box_aspect((1, 1, 1))
【解决方案2】:

以下代码不仅适用于长方体,也适用于任何多边形

分别输入 x、y 和 z 坐标

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from mpl_toolkits.mplot3d.art3d import Poly3DCollection

#input values
x=[1,10,50,100,150]
y=[1,300,350,250,50]
z=[0,1]
def edgecoord(pointx,pointy,pointz):
    edgex=[pointx[0],pointx[1],pointx[1],pointx[0]]
    edgey=[pointy[0],pointy[1],pointy[1],pointy[0]]
    edgez=[pointz[0],pointz[0],pointz[1],pointz[1]]
    return list(zip(edgex,edgey,edgez))

def coordConvert(x,y,lheight,uheight):
    if len(x) != len(y) and len(x)>2:
        return
    vertices=[]
    #Top layer
    vertices.append(list(zip(x,y,list(np.full(len(x),uheight)))))
    # Side layers
    for it in np.arange(len(x)):
        it1=it+1
        if it1>=len(x):
            it1=0
        vertices.append(edgecoord([x[it],x[it1]],[y[it],y[it1]],[lheight,uheight]))
    #Bottom layer
    vertices.append(list(zip(x,y,list(np.full(len(x),lheight)))))
    print(np.array(vertices))
    return vertices

vec=coordConvert(x,y,z[0],z[1])

plt.figure()
plt.subplot(111,projection='3d')
plt.gca().add_collection3d(Poly3DCollection(vec, alpha=.75,edgecolor='k', facecolor='teal'))
plt.xlim([0,200])
plt.ylim([0,400])
plt.show()

Polygon Prism

【讨论】:

    猜你喜欢
    • 2015-08-23
    • 1970-01-01
    • 2017-03-22
    • 2012-01-12
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多