matplotlib Three-dimensional plots Creating three-dimensional axes


Example

Matplotlib axes are two-dimensional by default. In order to create three-dimensional plots, we need to import the Axes3D class from the mplot3d toolkit, that will enable a new kind of projection for an axes, namely '3d':

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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

Beside the straightforward generalizations of two-dimensional plots (such as line plots, scatter plots, bar plots, contour plots), several surface plotting methods are available, for instance 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()

Axes3D with surface plot