We have so far discussed plotting in two dimensions. In fact, there are numerous occasions where we may need 3D data visualizations. Examples include illustrating more complex mathematical functions, terrain features, fluid dynamics in physics, as well as just showing one more facet of our data.
In Matplotlib, it can done by Axes3D in the mplot3d library within mpl_toolkits.
We just need to specify projection='3d' when defining an axes object after importing the library. Next, we just have to define the axes with x, y, and z coordinates. Supported plot types include scatter plot, line plot, bar plot, contour plots, wireframe plots, and surface plots with or without triangulation.
The following is an example of drawing a 3D surface plot:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.linspace(-2, 2, 60)
y = np.linspace(-2, 2, 60)
x, y = np.meshgrid(x, y)
r = np.sqrt(x**2 + y**2)
z = np.cos(r)
surf = ax.plot_surface(x, y, z, rstride=2, cstride=2, cmap='viridis', linewidth=0)
From the following screenshot, we see that the color gradient also helps in portraying the shape of the 3D plot: