Plotting a parametric 3D surface
In the previous recipe, we used plot_surface()
to plot a scalar field: that is, a function of the f(x, y) = z
form. However, matplotlib is able to plot a generic, parametric 3D surface. Let's demonstrate this by plotting a torus, which is a fairly simple parametric surface.
How to do it...
We are going to use plot_surface()
again to display a torus, using the following code:
import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt # Generate torus mesh angle = np.linspace(0, 2 * np.pi, 32) theta, phi = np.meshgrid(angle, angle) r, R = .25, 1. X = (R + r * np.cos(phi)) * np.cos(theta) Y = (R + r * np.cos(phi)) * np.sin(theta) Z = r * np.sin(phi) # Display the mesh fig = plt.figure() ax = fig.gca(projection = '3d') ax.set_xlim3d(-1, 1) ax.set_ylim3d(-1, 1) ax.set_zlim3d(-1, 1) ax.plot_surface(X, Y, Z, color = 'w', rstride = 1, cstride = 1) plt.show()
The preceding code will display our torus as follows:
How it works...
A torus...