Three-dimensional Plotting
Matplotlib - Introduction to 3D Plotting
Section titled “Matplotlib - Introduction to 3D Plotting”While Matplotlib was initially focused on 2D plotting, the mpl_toolkits.mplot3d toolkit extends its capabilities to create various types of three-dimensional visualizations. This toolkit is included with standard Matplotlib installations, so no separate installation is usually needed.
To enable 3D plotting, you need to create a special 3D Axes object. This is typically done by passing the projection='3d' keyword argument when creating an axes, usually via plt.figure().add_subplot() or plt.axes().
import matplotlib.pyplot as pltimport numpy as np
# No explicit import of mplot3d is strictly required# if using projection='3d', but it doesn't hurt:# from mpl_toolkits import mplot3d
# --- Create a Figure and a 3D Axes object ---fig = plt.figure(figsize=(8, 6))ax = fig.add_subplot(1, 1, 1, projection='3d')
# Alternative ways:# ax = plt.axes(projection='3d')# fig, ax = plt.subplots(subplot_kw={'projection': '3d'})
# Now 'ax' is a 3D Axes object, ready for 3D plotting commands.Once you have a 3D Axes object (ax), you can use its specific methods to create various 3D plots.
Basic 3D Plot Types
Section titled “Basic 3D Plot Types”1. 3D Line Plot (ax.plot3D)
Section titled “1. 3D Line Plot (ax.plot3D)”The simplest 3D plot connects points defined by (x, y, z) coordinates with lines.
# Example data for a 3D helixz_line = np.linspace(0, 15, 1000)x_line = np.sin(z_line)y_line = np.cos(z_line)
# Plot the 3D lineax.plot3D(x_line, y_line, z_line, color='gray', label='Helix')ax.set_title('3D Line Plot Example')ax.set_xlabel('X')ax.set_ylabel('Y')ax.set_zlabel('Z')ax.legend()2. 3D Scatter Plot (ax.scatter3D)
Section titled “2. 3D Scatter Plot (ax.scatter3D)”Plots individual markers at specified (x, y, z) coordinates. Useful for visualizing point clouds or discrete data points in 3D space. You can vary marker size (s) and color (c) based on other variables.
# Example data for a 3D scatter plotnp.random.seed(42)z_scatter = 15 * np.random.random(100)x_scatter = np.sin(z_scatter) + 0.1 * np.random.randn(100)y_scatter = np.cos(z_scatter) + 0.1 * np.random.randn(100)
# Color points by their z-value (optional)colors = z_scatter
# Plot the 3D scatter pointssc = ax.scatter3D(x_scatter, y_scatter, z_scatter, c=colors, cmap='viridis', s=50, alpha=0.7, label='Random Points')ax.set_title('3D Scatter Plot Example')ax.set_xlabel('X')ax.set_ylabel('Y')ax.set_zlabel('Z')
# Add a color bar if coloring by valuecbar = fig.colorbar(sc, label='Z value', shrink=0.5, aspect=10)ax.legend()This introduction covers creating the 3D axes and the basic line and scatter plots. Other common 3D plot types include:
- Contour Plots (
ax.contour3D): Draw contour lines in 3D space. - Wireframe Plots (
ax.plot_wireframe): Represent surfaces using a grid of lines. - Surface Plots (
ax.plot_surface): Represent surfaces using filled polygons, often colored by height.
These more complex plots often require data to be structured in 2D grids (using np.meshgrid). We will explore these in subsequent sections.
# Finalize and show the plot containing both examples (if run together)plt.show() # Display the figure