2015-11-05 83 views
2

我想用matplotlib將曲面繪製到立方體上。我正在嘗試使用ax.plot_surface(X, Y, Z),但我有點困惑。 X,YZ應該表示爲二維數組?在立方體上繪製曲面

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

points = np.array([[-1, -1, -1], 
         [1, -1, -1 ], 
         [1, 1, -1], 
         [-1, 1, -1], 
         [-1, -1, 1], 
         [1, -1, 1 ], 
         [1, 1, 1], 
         [-1, 1, 1]]) 

fig = plt.figure() 
ax = fig.add_subplot(111, projection='3d') 
# ax.plot_surface(X, Y, Z) # how? 
ax.scatter3D(points[:, 0], points[:, 1], points[:, 2]) 
ax.set_xlabel('X') 
ax.set_ylabel('Y') 
ax.set_zlabel('Z') 
plt.show() 

回答

5

立方體的每一個面是一個表面,你可以自己定義每個角落,或使用meshgrid:

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

points = np.array([[-1, -1, -1], 
         [1, -1, -1 ], 
         [1, 1, -1], 
         [-1, 1, -1], 
         [-1, -1, 1], 
         [1, -1, 1 ], 
         [1, 1, 1], 
         [-1, 1, 1]]) 

fig = plt.figure() 
ax = fig.add_subplot(111, projection='3d') 
r = [-1,1] 
X, Y = np.meshgrid(r, r) 
ax.plot_surface(X,Y,1, alpha=0.5) 
ax.plot_surface(X,Y,-1, alpha=0.5) 
ax.plot_surface(X,-1,Y, alpha=0.5) 
ax.plot_surface(X,1,Y, alpha=0.5) 
ax.plot_surface(1,X,Y, alpha=0.5) 
ax.plot_surface(-1,X,Y, alpha=0.5) 
ax.scatter3D(points[:, 0], points[:, 1], points[:, 2]) 
ax.set_xlabel('X') 
ax.set_ylabel('Y') 
ax.set_zlabel('Z') 
plt.show() 

enter image description here

X,Y和Z是(在相同)2D點列表:

>>> numpy.meshgrid([-1,1], [-1,1]) 
[array([[-1, 1], 
     [-1, 1]]), array([[-1, -1], 
     [ 1, 1]])]