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() ...

Get matplotlib Plotting Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.