Matplotlib轴默认为二维轴。为了创建三维图,我们需要Axes3D从mplot3d工具包中导入类,这将为轴启用一种新的投影,即'3d':
importmatplotlib.pyplotas plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d')
除了对二维图(例如线图,散点图,条形图,等高线图)的简单概括外,还提供了几种曲面图绘制方法,例如ax.plot_surface:
# generate example data import numpy as np x,y = np.meshgrid(np.linspace(-1,1,15),np.linspace(-1,1,15)) z = np.cos(x*np.pi)*np.sin(y*np.pi) # actual plotting example fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # rstride and cstride are row and column stride (step size) ax.plot_surface(x,y,z,rstride=1,cstride=1,cmap='hot') ax.set_xlabel(r'$x$') ax.set_ylabel(r'$y$') ax.set_zlabel(r'$\cos(\pi x) \sin(\pi y)$') plt.show()