2011-01-07 136 views
47

我是出于以下简单的问题的解决方案不成功浏览网页:使用顶点值绘制3D多边形的python-matplotlib


如何绘制3D多边形(比如填充矩形或三角形)? 我已经尝试了许多想法,但都失败了,请参阅:

from mpl_toolkits.mplot3d import Axes3D 
from matplotlib.collections import PolyCollection 
import matplotlib.pyplot as plt 
fig = plt.figure() 
ax = Axes3D(fig) 
x = [0,1,1,0] 
y = [0,0,1,1] 
z = [0,1,0,1] 
verts = [zip(x, y,z)] 
ax.add_collection3d(PolyCollection(verts),zs=z) 
plt.show() 

我感谢提前任何想法/评论。

更新基于公认的答案:

import mpl_toolkits.mplot3d as a3 
import matplotlib.colors as colors 
import pylab as pl 
import scipy as sp 

ax = a3.Axes3D(pl.figure()) 
for i in range(10000): 
    vtx = sp.rand(3,3) 
    tri = a3.art3d.Poly3DCollection([vtx]) 
    tri.set_color(colors.rgb2hex(sp.rand(3))) 
    tri.set_edgecolor('k') 
    ax.add_collection3d(tri) 
pl.show() 

下面是结果: enter image description here

+1

此解决方案如何针对Python 3.5进行更新?这个版本给我的错误是,'TypeError:'zip'类型的对象没有len()` – jlt199 2017-06-21 17:47:29

+1

@ jlt199只需使用`[list(zip(...))]`或者如果使用numpy> 1.10`[np。 stack([X,Y,Z],axis = 1)]`或`[np.stack([X,Y,Z],axis = 1)] – Y0da 2017-11-21 08:59:50

回答

43

我想你已经几乎得到了它。这是你想要的吗?

from mpl_toolkits.mplot3d import Axes3D 
from mpl_toolkits.mplot3d.art3d import Poly3DCollection 
import matplotlib.pyplot as plt 
fig = plt.figure() 
ax = Axes3D(fig) 
x = [0,1,1,0] 
y = [0,0,1,1] 
z = [0,1,0,1] 
verts = [zip(x, y,z)] 
ax.add_collection3d(Poly3DCollection(verts)) 
plt.show() 

alt text 您可能也有兴趣art3d.pathpatch_2d_to_3d。