We use 3D axes to show data in three dimensions. This helps us see relationships that are hard to understand in flat 2D charts.
3D axes with projection='3d' in Matplotlib
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
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
Matplotlib
fig = plt.figure() ax = fig.add_subplot(111, projection='3d')
Matplotlib
fig = plt.figure(figsize=(8,6)) ax = fig.add_subplot(111, projection='3d')
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()
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.
Practice
1. What does setting
projection='3d' do when creating axes in matplotlib?easy
Solution
Step 1: Understand the role of projection parameter
Theprojectionparameter in matplotlib axes defines the type of plot. Setting it to'3d'enables three-dimensional plotting.Step 2: Identify the effect of
This setting creates a 3D plot area where data can be visualized along x, y, and z axes.projection='3d'Final Answer:
It creates a 3D plot area to visualize data in three dimensions. -> Option AQuick Check:
projection='3d' = 3D plot area [OK]
Hint: projection='3d' means 3D plot space [OK]
Common Mistakes:
- Thinking it changes colors automatically
- Assuming it enables animation
- Believing it exports 3D files
2. Which of the following is the correct way to create a 3D axes object in matplotlib?
easy
Solution
Step 1: Recall the syntax for 3D axes creation
To create 3D axes, useplt.subplot()orplt.axes()withprojection='3d'.Step 2: Check each option
ax = plt.subplot(111, projection='3d')is correct. The other options use incorrect functions or parameters.Final Answer:
ax = plt.subplot(111, projection='3d') -> Option BQuick Check:
Use subplot with projection='3d' = correct syntax [OK]
Hint: Use subplot or axes with projection='3d' [OK]
Common Mistakes:
- Using plt.plot() with projection
- Passing projection to plt.figure()
- Calling non-existent plt.axes3d()
3. What will the following code output?
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter([1,2], [3,4], [5,6]) print(type(ax))
medium
Solution
Step 1: Understand the code creating 3D axes
The code creates a figure, then adds a 3D subplot withprojection='3d'. This returns an Axes3DSubplot object.Step 2: Check the printed type
Printingtype(ax)will show the class of the 3D axes object, which isAxes3DSubplot.Final Answer:
<class 'matplotlib.axes._subplots.Axes3DSubplot'> -> Option AQuick Check:
3D subplot type = Axes3DSubplot [OK]
Hint: 3D subplot returns Axes3DSubplot type [OK]
Common Mistakes:
- Expecting base Axes type
- Confusing syntax or runtime errors
- Not importing Axes3D
4. Identify the error in this code snippet:
import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) ax = plt.axes(projection='3d') ax.plot([1,2,3], [4,5,6], [7,8,9]) plt.show()
medium
Solution
Step 1: Analyze axes creation
The code first createsaxwithfig.add_subplot(111)(2D axes), then immediately overwritesaxwithplt.axes(projection='3d'). This is confusing and may cause unexpected behavior.Step 2: Understand the problem
Overwritingaxwithout using the figure's subplot can cause the 3D axes to not be linked to the figure properly.Final Answer:
Calling plt.axes() after fig.add_subplot() overwrites ax incorrectly. -> Option CQuick Check:
Overwriting ax with plt.axes() causes confusion [OK]
Hint: Avoid overwriting axes objects; create 3D axes once [OK]
Common Mistakes:
- Forgetting to import Axes3D (not needed in recent matplotlib)
- Thinking plot() can't take 3 lists
- Missing plt.show() parentheses
5. You want to plot a 3D scatter plot with points colored by their z-value. Which code snippet correctly creates the 3D axes and colors the points accordingly?
hard
Solution
Step 1: Create 3D axes correctly
Usefig.add_subplot(111, projection='3d')to create 3D axes linked to the figure.Step 2: Color points by z-value
Passc=zand a colormap likecmap='viridis'toscatter()to color points based on z.Final Answer:
fig = plt.figure() ax = fig.add_subplot(111, projection='3d') z = [1, 2, 3] ax.scatter([1,2,3], [4,5,6], z, c=z, cmap='viridis') plt.show() -> Option DQuick Check:
3D axes + c=z + cmap = fig = plt.figure() ax = fig.add_subplot(111, projection='3d') z = [1, 2, 3] ax.scatter([1,2,3], [4,5,6], z, c=z, cmap='viridis') plt.show() [OK]
Hint: Use c=z and cmap for coloring in 3D scatter [OK]
Common Mistakes:
- Using color='z' instead of c=z
- Creating 2D axes for 3D data
- Not specifying projection='3d'
