We use 3D axes to show data in three dimensions. This helps us see relationships that are hard to understand in flat 2D charts.
0
0
3D axes with projection='3d' in Matplotlib
Introduction
When you want to visualize points or shapes in space, like stars or buildings.
When you have three variables and want to see how they relate together.
When you want to show a surface or a 3D curve.
When you want to explore data from different angles by rotating the view.
Syntax
Matplotlib
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection='3d')
The key part is projection='3d' which tells matplotlib to create 3D axes.
You need to import Axes3D from mpl_toolkits.mplot3d to enable 3D plotting.
Examples
Create a figure and add one 3D subplot.
Matplotlib
fig = plt.figure() ax = fig.add_subplot(111, projection='3d')
Create a bigger figure with 3D axes.
Matplotlib
fig = plt.figure(figsize=(8,6)) ax = fig.add_subplot(111, projection='3d')
Create two 3D plots side by side.
Matplotlib
fig = plt.figure() ax1 = fig.add_subplot(121, projection='3d') ax2 = fig.add_subplot(122, projection='3d')
Sample Program
This program creates a 3D surface plot of a wave pattern. It shows how to set up 3D axes and plot a surface using plot_surface.
Matplotlib
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np # Create data 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)) # Create figure and 3D axes fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # Plot surface surf = ax.plot_surface(X, Y, Z, cmap='viridis') # Add labels ax.set_xlabel('X axis') ax.set_ylabel('Y axis') ax.set_zlabel('Z axis') # Show plot plt.show()
OutputSuccess
Important Notes
3D plots can be rotated interactively in the plot window to see different angles.
Not all matplotlib plot types support 3D, so use functions like plot_surface, scatter, or plot on 3D axes.
Summary
Use projection='3d' to create 3D axes in matplotlib.
3D plots help visualize data with three variables or spatial shapes.
You can plot surfaces, scatter points, and lines in 3D.