2012-06-21 505 views
51

我用matplotlib搜索如何用盡可能少的指令繪製東西,但我在文檔中找不到任何幫助。Python/matplotlib:繪製一個3d立方體,一個球體和一個向量?

我要繪製的以下東西:

  • 線框立方體在0爲中心具有2
  • 一個「線框」球在0爲中心具有1
  • 一個半徑的邊長點座標[0,0,0]
  • 啓動在這一點上,去到一個向量[1,1,1]

如何做到這一點?

+3

另外檢查[mayavi2](http://docs.enthought.com/mayavi/mayavi/auto/examples.html)。它有點依賴性很大,但有一些非常棒的高級命令。如果需要,我可以根據這個軟件包制定更詳細的答案。 。 。 – meawoppl

回答

134

這是一個有點複雜,但您可以通過下面的代碼繪製的所有對象:

from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 
import numpy as np 
from itertools import product, combinations 


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

# draw cube 
r = [-1, 1] 
for s, e in combinations(np.array(list(product(r, r, r))), 2): 
    if np.sum(np.abs(s-e)) == r[1]-r[0]: 
     ax.plot3D(*zip(s, e), color="b") 

# draw sphere 
u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j] 
x = np.cos(u)*np.sin(v) 
y = np.sin(u)*np.sin(v) 
z = np.cos(v) 
ax.plot_wireframe(x, y, z, color="r") 

# draw a point 
ax.scatter([0], [0], [0], color="g", s=100) 

# draw a vector 
from matplotlib.patches import FancyArrowPatch 
from mpl_toolkits.mplot3d import proj3d 


class Arrow3D(FancyArrowPatch): 

    def __init__(self, xs, ys, zs, *args, **kwargs): 
     FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs) 
     self._verts3d = xs, ys, zs 

    def draw(self, renderer): 
     xs3d, ys3d, zs3d = self._verts3d 
     xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) 
     self.set_positions((xs[0], ys[0]), (xs[1], ys[1])) 
     FancyArrowPatch.draw(self, renderer) 

a = Arrow3D([0, 1], [0, 1], [0, 1], mutation_scale=20, 
      lw=1, arrowstyle="-|>", color="k") 
ax.add_artist(a) 
plt.show() 

output_figure

5

繪製只是箭頭,還有一個更簡單的方法: -

from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 
fig = plt.figure() 
ax = fig.gca(projection='3d') 
ax.set_aspect("equal") 

#draw the arrow 
ax.quiver(0,0,0,1,1,1,length=1.0) 

plt.show() 

顫抖實際上可以用來一次繪製多個矢量。的用法如下: - [從http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html?highlight=quiver#mpl_toolkits.mplot3d.Axes3D.quiver]

顫動(X,Y,Z,U,V,W,** kwargs)

參數:

X,Y,Z : 箭頭位置的x,y和z座標

U,V,W:箭頭向量 的x,y和z分量

參數可以是數組或標量。

關鍵字參數:

長度: [1.0 |浮子] 每個顫動的長度,默認至1.0,單位是與軸

相同

arrow_length_ratio: [0.3 | float] 箭頭相對於箭袋的比率,默認爲0.3

pivot: ['tail'| '中間'| 'tip'] 在網格點的箭頭部分;箭頭圍繞這一點旋轉,因此名稱樞軸。默認爲'尾'

正常化: [False | True] 當爲True時,所有箭頭的長度將相同。默認爲False,箭頭的長度取決於u,v,w的值。