I would like to plot surfaces to a cube with matplotlib
. I am trying to use ax.plot_surface(X, Y, Z)
, however I am a bit confused. What should the X
, Y
and Z
represent as 2D arrays?
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()
Each face of the cube is a surface for which you can either define each corner yourself, or use 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)
z = np.array([[1, 1]])
ax.plot_surface(X,Y, 1*z, alpha=0.5)
ax.plot_surface(X,Y,-1*z, alpha=0.5)
ax.plot_surface(X,-1*z,Y, alpha=0.5)
ax.plot_surface(X,1*z,Y, alpha=0.5)
ax.plot_surface(1*z,X,Y, alpha=0.5)
ax.plot_surface(-1*z,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()
X,Y, and Z are (the same) list of 2D points:
>>> numpy.meshgrid([-1,1], [-1,1])
[array([[-1, 1],
[-1, 1]]), array([[-1, -1],
[ 1, 1]])]