How to Create 3D Plot in Matplotlib: Simple Guide
To create a 3D plot in
matplotlib, first import Axes3D from mpl_toolkits.mplot3d and create a 3D axes using fig.add_subplot(projection='3d'). Then use plotting methods like plot3D, scatter3D, or plot_surface on the 3D axes to visualize data in three dimensions.Syntax
To create a 3D plot, you need to:
- Import
Axes3Dfrommpl_toolkits.mplot3d. - Create a figure with
plt.figure(). - Add a 3D subplot with
fig.add_subplot(111, projection='3d'). - Use 3D plotting methods like
plot3D,scatter3D, orplot_surfaceon the 3D axes.
python
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # Use ax.plot3D(), ax.scatter3D(), or ax.plot_surface() here plt.show()
Example
This example shows how to create a simple 3D line plot using plot3D. It plots a curve in 3D space with x, y, and z coordinates.
python
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # Create data z = np.linspace(0, 1, 100) x = z * np.sin(25 * z) y = z * np.cos(25 * z) # Plot 3D line ax.plot3D(x, y, z, 'blue') plt.show()
Output
A 3D line plot showing a spiral curve in blue color.
Common Pitfalls
Common mistakes when creating 3D plots include:
- Not specifying
projection='3d'when adding the subplot, which results in a 2D plot. - Forgetting to import
Axes3Dfrommpl_toolkits.mplot3d. - Using 2D plotting methods like
plt.plot()instead of 3D methods on the 3D axes.
Always use the 3D axes object methods like ax.plot3D() or ax.scatter3D() for 3D plotting.
python
import matplotlib.pyplot as plt fig = plt.figure() # Missing projection='3d' leads to 2D plot ax = fig.add_subplot(111) # Wrong # This will plot a 2D line, not 3D ax.plot([1, 2, 3], [4, 5, 6]) plt.show() # Correct way: from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot3D([1, 2, 3], [4, 5, 6], [7, 8, 9]) plt.show()
Output
First plot: 2D line plot with no 3D effect.
Second plot: 3D line plot with points in 3D space.
Quick Reference
Here is a quick summary of common 3D plotting methods on the 3D axes object:
| Method | Description |
|---|---|
| plot3D(x, y, z) | Draws a 3D line plot connecting points. |
| scatter3D(x, y, z) | Creates a 3D scatter plot with points. |
| plot_surface(X, Y, Z) | Plots a 3D surface from grid data. |
| bar3d(x, y, z, dx, dy, dz) | Draws 3D bars (histogram style). |
| contour3D(X, Y, Z) | Draws 3D contour lines. |
Key Takeaways
Always create 3D axes with projection='3d' to enable 3D plotting.
Use 3D-specific methods like plot3D or scatter3D on the 3D axes object.
Import Axes3D from mpl_toolkits.mplot3d to access 3D plotting features.
Common errors include missing projection or using 2D plot methods on 3D axes.
3D plots help visualize data with three variables in a clear spatial way.