3D Plotting Setup in Matplotlib
Learn how to create three-dimensional plotting areas using Matplotlib's mplot3d toolkit and understand the basic structure required for 3D visualizations.
1. Learning Objectives
After completing this lesson, you will understand how to:
- Understand three-dimensional plotting.
- Understand the Matplotlib mplot3d toolkit.
- Create a 3D plotting area using
projection="3d". - Understand X, Y and Z axes.
- Create basic 3D scatter and line visualizations.
- Customize the appearance of a 3D plotting area.
2. What is 3D Plotting?
Three-dimensional plotting is a technique used to represent data using three axes: X, Y and Z. Unlike a traditional two-dimensional chart, a 3D chart can display an additional dimension.
Matplotlib provides the mplot3d toolkit to create
three-dimensional plots. It supports different types of
visualizations, including 3D lines, scatter plots, surface plots
and wireframes.
2D vs 3D Plotting
| Feature | 2D Plotting | 3D Plotting |
|---|---|---|
| Axes | X and Y | X, Y and Z |
| Dimensions | Two-dimensional | Three-dimensional |
| Data representation | Position on a flat plotting area | Position in three-dimensional space |
| Examples | Line charts and bar charts | 3D scatter and surface plots |
3. Understanding the Three Axes
A 3D plotting area uses three coordinate axes. Each axis represents one dimension of the data.
X, Y and Z axes represent the three dimensions of a 3D coordinate system.
| Axis | Description | Example |
|---|---|---|
| X-axis | Represents the first dimension. | Experience |
| Y-axis | Represents the second dimension. | Salary |
| Z-axis | Represents the third dimension. | Performance score |
4. Import Required Libraries
Before creating a 3D plot, import Matplotlib's pyplot module. You also need the 3D plotting toolkit provided by Matplotlib.
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
These imports are used for the following purposes:
| Library | Purpose |
|---|---|
matplotlib.pyplot |
Creates and manages Figures and plotting areas. |
mpl_toolkits.mplot3d |
Provides three-dimensional plotting support. |
numpy |
Creates and manages numerical arrays and coordinates. |
projection="3d" automatically activates the 3D
projection. Importing Axes3D explicitly is generally
not necessary, but it is still useful to recognize in older examples.
5. Create Your First 3D Plotting Area
To create a 3D plotting area, use plt.figure() and
fig.add_subplot(). Set the projection parameter to
"3d".
Basic Syntax
fig = plt.figure()
ax = fig.add_subplot(
111,
projection="3d"
)
Here:
plt.figure()creates a new Figure.add_subplot()adds a plotting area to the Figure.111represents one row, one column and the first subplot.projection="3d"creates a three-dimensional Axes object.
Complete Example
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(
111,
projection="3d"
)
ax.set_title("My First 3D Plot")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.show()
Output
Figure: My First 3D Plot
A three-dimensional plotting area is displayed.
X-axis: X-axis
Y-axis: Y-axis
Z-axis: Z-axis
No data points are plotted in this example.
6. Create a 3D Axes Using plt.subplots()
You can also create a 3D plotting area using
plt.subplots(). This approach is convenient when
you want to manage the Figure and Axes together.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(
figsize=(8, 6),
subplot_kw={"projection": "3d"}
)
ax.set_title("3D Plot Using Subplots")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.show()
Output
Figure: 3D Plot Using Subplots
A Figure containing one 3D Axes object is displayed.
The plotting area includes X, Y and Z axes.
plt.subplots(subplot_kw={"projection": "3d"})
when you want a clean and convenient way to create a 3D Axes object.
7. Plot Basic 3D Data Points
After creating a 3D Axes object, you can use the
scatter() method to display points using X, Y and Z
coordinate values.
Example: Basic 3D Scatter Plot
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 5, 3]
z = [5, 3, 4, 2, 6]
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(
111,
projection="3d"
)
ax.scatter(
x,
y,
z,
color="blue",
s=80
)
ax.set_title("Basic 3D Scatter Plot")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.show()
Output
Figure: Basic 3D Scatter Plot
A 3D scatter plot displays five points.
Point coordinates:
(1, 2, 5)
(2, 4, 3)
(3, 1, 4)
(4, 5, 2)
(5, 3, 6)
8. Customize the 3D Plot
Matplotlib provides different methods to customize the appearance and viewing position of a 3D plotting area.
8.1 Set Axis Labels
ax.set_xlabel("Experience")
ax.set_ylabel("Salary")
ax.set_zlabel("Performance")
8.2 Set Axis Limits
ax.set_xlim(0, 10)
ax.set_ylim(0, 100)
ax.set_zlim(0, 50)
8.3 Set the Viewing Angle
ax.view_init(
elev=30,
azim=45
)
8.4 Add a Title
ax.set_title(
"Employee Performance - 3D View"
)
Complete Customization Example
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [20, 30, 40, 50, 60]
z = [10, 25, 20, 40, 45]
fig = plt.figure(figsize=(9, 6))
ax = fig.add_subplot(
111,
projection="3d"
)
ax.scatter(
x,
y,
z,
color="purple",
s=100
)
ax.set_title("Employee Performance - 3D View")
ax.set_xlabel("Experience")
ax.set_ylabel("Salary")
ax.set_zlabel("Performance")
ax.set_xlim(0, 6)
ax.set_ylim(0, 70)
ax.set_zlim(0, 50)
ax.view_init(
elev=30,
azim=45
)
plt.tight_layout()
plt.show()
Output
Figure: Employee Performance - 3D View
A customized 3D scatter plot is displayed.
X-axis: Experience
Y-axis: Salary
Z-axis: Performance
The plot uses purple markers and a customized viewing angle.
9. Important 3D Axes Methods
| Method | Purpose |
|---|---|
set_xlabel() |
Sets the X-axis label. |
set_ylabel() |
Sets the Y-axis label. |
set_zlabel() |
Sets the Z-axis label. |
set_xlim() |
Sets the X-axis limits. |
set_ylim() |
Sets the Y-axis limits. |
set_zlim() |
Sets the Z-axis limits. |
view_init() |
Changes the viewing elevation and azimuth. |
scatter() |
Creates a 3D scatter plot. |
plot() |
Creates a 3D line plot when X, Y and Z values are supplied. |
plot_surface() |
Creates a 3D surface plot. |
10. Common Mistakes
| Mistake | Explanation | Solution |
|---|---|---|
| Missing 3D projection | A normal 2D Axes object is created. | Use projection="3d". |
| Missing Z values | 3D plotting methods require three coordinate dimensions. | Provide valid X, Y and Z data. |
| Different array lengths | Coordinate arrays cannot be combined correctly when their shapes are incompatible. | Check the dimensions of the input data. |
| Incorrect axis labels | Data dimensions become difficult to understand. | Use descriptive X, Y and Z labels. |
| Incorrect viewing angle | Some points or surfaces may be difficult to inspect. | Adjust the elevation and azimuth values. |
projection="3d". Creating a normal 2D Axes and calling
3D plotting methods on it will not work as expected.
11. Best Practices
- Use
projection="3d"to create a 3D Axes object. - Use NumPy arrays when working with large numerical datasets.
- Provide compatible X, Y and Z coordinate arrays.
- Always add meaningful axis labels and chart titles.
- Choose a suitable viewing angle for better data visibility.
- Set axis limits when you need a consistent viewing range.
- Use 3D plots only when the third dimension provides useful information.
12. Practical Activity
Student Performance 3D Visualization
Create a 3D scatter plot to visualize student performance.
Requirements:
- Create a list of student study hours.
- Create a list of attendance percentages.
- Create a list of examination scores.
- Create a 3D Axes object using Matplotlib.
- Plot the values using
ax.scatter(). - Set the X-axis label to Study Hours.
- Set the Y-axis label to Attendance.
- Set the Z-axis label to Exam Score.
- Add a chart title and customize the viewing angle.
13. Practice Questions
- What is 3D plotting?
- What is the purpose of the mplot3d toolkit?
- How do you create a 3D Axes object in Matplotlib?
- What does
projection="3d"do? - What are X, Y and Z axes?
- How do you create a 3D scatter plot?
- What is the purpose of
view_init()? - How do you set limits for the Z-axis?
- What is the difference between 2D and 3D plotting?
- Which method is used to create a 3D surface plot?
Summary
Matplotlib supports three-dimensional visualizations through its mplot3d toolkit. A 3D plotting area represents data using X, Y and Z coordinate axes.
You can create a 3D Axes object using
fig.add_subplot(projection="3d") or
plt.subplots(subplot_kw={"projection": "3d"}).
After creating the Axes, you can use methods such as
scatter(), plot() and
plot_surface().
Axis labels, axis limits and viewing angles help make 3D visualizations easier to understand. These fundamentals are useful when creating advanced 3D charts and data visualizations.