2011-01-07 221 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。