📘 Matplotlib Tutorial – Chapter 9: 3D Plotting in Matplotlib
Matplotlib is not limited to 2D visualizations — it can also create stunning 3D plots using the mpl_toolkits.mplot3d module. This chapter teaches you how to visualize complex datasets in three dimensions, making it easier to interpret multi-variable relationships.
✅ Why Use 3D Plots?
3D visualizations help in understanding spatial data, mathematical functions, and multi-dimensional datasets. They’re especially useful in fields like machine learning, physics, and engineering for visualizing models and surfaces.
✅ Setting Up 3D Axes
To create 3D plots, you must first enable a 3D projection using projection='3d' when defining your axes.
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
plt.title("3D Plot Setup Example")
plt.show()
Once the 3D axes are initialized, you can start plotting lines, surfaces, and points in three dimensions.
✅ 1. 3D Line Plot
A 3D line plot is useful for visualizing continuous paths or trends in 3D space.
z = np.linspace(0, 20, 100)
x = np.sin(z)
y = np.cos(z)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(x, y, z, label="3D Spiral", color="purple")
ax.set_title("3D Line Plot Example")
ax.legend()
plt.show()
This creates a helical or spiral pattern using sine and cosine functions, demonstrating continuous motion in 3D space.
✅ 2. 3D Scatter Plot
Scatter plots show individual data points in 3D. They are perfect for showing spatial clusters or point distributions.
x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, color='blue', marker='o')
ax.set_title("3D Scatter Plot Example")
plt.show()
You can use different colors and marker sizes to highlight groups or add meaning to your data visualization.
✅ 3. 3D Surface Plot
Surface plots are ideal for displaying mathematical functions or terrain-like surfaces.
X = np.linspace(-5, 5, 50)
Y = np.linspace(-5, 5, 50)
X, Y = np.meshgrid(X, Y)
Z = np.sin(np.sqrt(X**2 + Y**2))
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(X, Y, Z, cmap='viridis')
fig.colorbar(surf)
ax.set_title("3D Surface Plot Example")
plt.show()
The plot_surface() method creates a smooth surface based on the data grid, while fig.colorbar() adds a color legend.
✅ 4. 3D Wireframe Plot
Wireframe plots show surfaces as a mesh grid — useful for understanding structure without full shading.
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(X, Y, Z, color='gray')
ax.set_title("3D Wireframe Plot Example")
plt.show()
These plots are lighter to render and useful when you want to emphasize surface structure.
✅ 5. 3D Contour Plot
3D contour plots show slices or contour lines of a 3D surface, helping identify peaks and valleys.
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.contour3D(X, Y, Z, 50, cmap='coolwarm')
ax.set_title("3D Contour Plot Example")
plt.show()
You can control the number of contours and apply colormaps to highlight height variations.
✅ 6. Customizing 3D Axes
You can label axes, change viewing angles, and adjust limits to improve the visualization.
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
ax.view_init(elev=30, azim=45) # Set angle of view
The view_init() method allows you to rotate and tilt the 3D plot for the best viewing angle.
✅ 7. Color Mapping on Surfaces
You can map colors to surface height using facecolors or cmap to represent variable intensity.
surf = ax.plot_surface(X, Y, Z, cmap='plasma', edgecolor='none')
fig.colorbar(surf, ax=ax, shrink=0.6, aspect=10)
This technique makes 3D surfaces more meaningful by showing value gradients visually.
✅ 8. Combining Multiple 3D Plots
You can create multiple 3D subplots within one figure using plt.subplots() and the subplot_kw parameter.
fig, axes = plt.subplots(1, 2, subplot_kw={'projection':'3d'}, figsize=(10,5))
axes[0].plot_surface(X, Y, Z, cmap='viridis')
axes[0].set_title("Surface Plot")
axes[1].contour3D(X, Y, Z, 50, cmap='inferno')
axes[1].set_title("Contour Plot")
plt.tight_layout()
plt.show()
This helps compare multiple 3D perspectives side by side for deeper insights.
✅ 9. Saving 3D Plots
3D plots can be saved in image formats like PNG, JPG, or SVG using plt.savefig() just like 2D plots.
plt.savefig('3d_plot_example.png', dpi=300, bbox_inches='tight')
✅ Best Practices for 3D Visualization
- Use color gradients wisely — avoid too many bright contrasts.
- Label all three axes clearly.
- Choose appropriate viewing angles for better perspective.
- Keep the plot simple — 3D visuals can easily become cluttered.
✅ Summary
In this chapter, you learned how to create 3D line, scatter, surface, wireframe, and contour plots using Matplotlib. You also discovered how to customize axes, use color maps, and save your 3D visualizations.
Next, we’ll explore Chapter 10: Plotting with Pandas and NumPy — where you’ll learn how Matplotlib integrates with these powerful data analysis libraries to simplify visualization workflows.
