3D Camera View and Perspective
Learn how to control the viewing angle of three-dimensional plots using Matplotlib. Explore elevation, azimuth, roll, camera perspective and interactive 3D navigation.
1. Learning Objectives
After completing this lesson, you will understand how to:
- Understand camera positioning in 3D plots.
- Customize elevation and azimuth angles.
- Use the roll parameter to rotate the camera view.
- Control the camera projection type.
- Customize the 3D viewing perspective.
- Understand interactive rotation of 3D plots.
- Save a 3D visualization with a selected camera angle.
2. What is a Camera View in 3D Plotting?
A camera view determines how a three-dimensional plotting area appears on a two-dimensional screen. It controls the direction from which the viewer observes the 3D data.
Matplotlib provides camera-related settings through the 3D Axes object. By adjusting these settings, you can display the same data from different viewing directions.
Why Camera View is Important
- It helps reveal hidden parts of a 3D visualization.
- It makes surface shapes easier to understand.
- It helps compare different 3D data structures.
- It improves the presentation of 3D charts.
- It helps select a useful viewing angle for reports.
3. Understanding Elevation and Azimuth
Matplotlib uses elevation and azimuth angles to control the position of the camera around a 3D plotting area.
| Parameter | Description | Effect |
|---|---|---|
elev |
Elevation angle in degrees. | Changes the vertical viewing position. |
azim |
Azimuth angle in degrees. | Changes the horizontal viewing direction. |
roll |
Camera roll angle in degrees. | Rotates the camera view around its viewing direction. |
Elevation changes the vertical viewing angle, while azimuth changes the horizontal viewing direction.
4. The view_init() Method
The view_init() method changes the viewing angle
of a 3D Axes object.
Basic Syntax
ax.view_init(
elev=None,
azim=None,
roll=None
)
Parameters:
elev: Controls the elevation angle.azim: Controls the azimuth angle.roll: Controls camera roll where supported.
Example: Set a Custom Camera Angle
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 30)
y = np.linspace(-5, 5, 30)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
fig = plt.figure(figsize=(9, 6))
ax = fig.add_subplot(
111,
projection="3d"
)
ax.plot_surface(
X,
Y,
Z,
cmap="viridis"
)
ax.view_init(
elev=30,
azim=45
)
ax.set_title("3D Plot with Custom Camera View")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.show()
Output
Figure: 3D Plot with Custom Camera View
A bowl-shaped 3D surface is displayed.
Elevation: 30 degrees
Azimuth: 45 degrees
The camera observes the surface from an elevated diagonal direction.
5. Change the Elevation Angle
Elevation controls how high or low the camera looks at the 3D plotting area. Changing this value can reveal different surface features.
Example: Different Elevation Values
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-4, 4, 30)
y = np.linspace(-4, 4, 30)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
fig = plt.figure(figsize=(12, 4))
elevations = [15, 35, 65]
for i, angle in enumerate(elevations):
ax = fig.add_subplot(
1,
3,
i + 1,
projection="3d"
)
ax.plot_surface(
X,
Y,
Z,
cmap="viridis"
)
ax.view_init(
elev=angle,
azim=45
)
ax.set_title(f"Elevation: {angle}°")
plt.tight_layout()
plt.show()
Output
Figure: Comparison of Elevation Angles
Three 3D surface plots are displayed.
First plot: Elevation 15 degrees.
Second plot: Elevation 35 degrees.
Third plot: Elevation 65 degrees.
Each plot uses the same data and azimuth angle.
Only the camera elevation changes.
6. Change the Azimuth Angle
Azimuth controls the horizontal direction from which the camera views the 3D plotting area. It is useful when you want to inspect a surface from different sides.
Example: Different Azimuth Values
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-4, 4, 30)
y = np.linspace(-4, 4, 30)
X, Y = np.meshgrid(x, y)
Z = X**2 - Y**2
fig = plt.figure(figsize=(12, 4))
azimuths = [0, 90, 180]
for i, angle in enumerate(azimuths):
ax = fig.add_subplot(
1,
3,
i + 1,
projection="3d"
)
ax.plot_surface(
X,
Y,
Z,
cmap="coolwarm"
)
ax.view_init(
elev=30,
azim=angle
)
ax.set_title(f"Azimuth: {angle}°")
plt.tight_layout()
plt.show()
Output
Figure: Comparison of Azimuth Angles
Three 3D surface plots are displayed.
First plot: Azimuth 0 degrees.
Second plot: Azimuth 90 degrees.
Third plot: Azimuth 180 degrees.
Each plot uses the same data and elevation angle.
Only the horizontal camera direction changes.
7. Understand the Camera Roll Angle
The roll parameter rotates the camera view around its viewing direction. It changes the orientation of the displayed image without changing the underlying data coordinates.
roll parameter
is available in modern Matplotlib versions. Check your installed
Matplotlib version if an older environment does not support it.
Example: Camera Roll
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-4, 4, 30)
y = np.linspace(-4, 4, 30)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
fig = plt.figure(figsize=(9, 6))
ax = fig.add_subplot(
111,
projection="3d"
)
ax.plot_surface(
X,
Y,
Z,
cmap="plasma"
)
ax.view_init(
elev=30,
azim=45,
roll=20
)
ax.set_title("3D Camera Roll Example")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.show()
Output
Figure: 3D Camera Roll Example
A wave-shaped 3D surface is displayed.
Elevation: 30 degrees
Azimuth: 45 degrees
Roll: 20 degrees
The camera image is rotated around its viewing direction.
8. Compare Multiple Camera Views
You can create multiple 3D subplots to compare different camera positions. This is useful when selecting the best angle for presenting a 3D dataset.
Example: Three Camera Views
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 40)
y = np.linspace(-5, 5, 40)
X, Y = np.meshgrid(x, y)
Z = np.cos(np.sqrt(X**2 + Y**2))
views = [
(20, 30),
(40, 60),
(60, 120)
]
fig = plt.figure(figsize=(14, 5))
for i, (elev, azim) in enumerate(views):
ax = fig.add_subplot(
1,
3,
i + 1,
projection="3d"
)
ax.plot_surface(
X,
Y,
Z,
cmap="viridis"
)
ax.view_init(
elev=elev,
azim=azim
)
ax.set_title(
f"Elev={elev}, Azim={azim}"
)
plt.tight_layout()
plt.show()
Output
Figure: Three Camera View Comparison
Three plots display the same 3D surface.
Plot 1: Elevation 20, Azimuth 30.
Plot 2: Elevation 40, Azimuth 60.
Plot 3: Elevation 60, Azimuth 120.
The camera position changes in each subplot.
9. Orthographic and Perspective Projection
Matplotlib supports different projection types for displaying three-dimensional plots. The two commonly used options are perspective and orthographic projection.
| Projection | Description | Visual Effect |
|---|---|---|
| Perspective | Uses perspective projection to represent depth. | Objects appear smaller as they are farther away. |
| Orthographic | Uses parallel projection lines. | Objects do not become smaller based on distance. |
Example: Set Orthographic Projection
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(
111,
projection="3d"
)
ax.plot_surface(
X,
Y,
Z,
cmap="viridis"
)
ax.set_proj_type("ortho")
ax.set_title("Orthographic 3D Projection")
plt.show()
Output
Figure: Orthographic 3D Projection
A 3D surface is displayed using orthographic projection.
Parallel projection is used.
The apparent size of objects does not change with distance.
Example: Set Perspective Projection
ax.set_proj_type("persp")
Output
Projection Type: Perspective
The 3D Axes uses perspective projection.
Depth is represented using perspective scaling.
10. Control the Camera Distance
Matplotlib's 3D Axes provides the dist attribute
for controlling the camera distance in versions where this
attribute is available. It is deprecated in recent Matplotlib
versions, so avoid relying on it in new projects.
dist attribute
is deprecated in recent Matplotlib releases. Prefer adjusting
the viewing limits, figure size and projection settings for
modern plotting workflows.
Recommended Alternative: Adjust Axis Limits
ax.set_xlim(-5, 5)
ax.set_ylim(-5, 5)
ax.set_zlim(-2, 2)
ax.set_box_aspect((1, 1, 0.6))
Output
3D Camera Display
X-axis range: -5 to 5
Y-axis range: -5 to 5
Z-axis range: -2 to 2
The plotting box uses a customized aspect ratio.
11. Interactive Rotation of 3D Plots
Matplotlib supports interactive 3D navigation when used with a suitable interactive backend. In an interactive window, you can use the mouse to rotate and inspect the plot.
Example: Interactive 3D Plot
import matplotlib.pyplot as plt
import numpy as np
plt.ion()
x = np.linspace(-5, 5, 40)
y = np.linspace(-5, 5, 40)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
fig = plt.figure(figsize=(9, 6))
ax = fig.add_subplot(
111,
projection="3d"
)
ax.plot_surface(
X,
Y,
Z,
cmap="viridis"
)
ax.set_title("Interactive 3D Surface")
plt.show()
plt.ioff()
Output
Figure: Interactive 3D Surface
A 3D surface is displayed in an interactive Matplotlib window
when the selected backend supports interactive navigation.
Mouse interaction can be used to rotate and inspect the surface.
12. Save a 3D Plot with a Selected Camera View
After selecting a suitable camera angle, you can save the
visualization using savefig().
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 40)
y = np.linspace(-5, 5, 40)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
fig = plt.figure(figsize=(9, 6))
ax = fig.add_subplot(
111,
projection="3d"
)
ax.plot_surface(
X,
Y,
Z,
cmap="viridis"
)
ax.view_init(
elev=35,
azim=50
)
ax.set_title("Saved 3D Camera View")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.savefig(
"camera_view.png",
dpi=300,
bbox_inches="tight"
)
plt.show()
Output
File: camera_view.png
A 3D surface plot is saved as a PNG image.
Resolution: 300 DPI
Camera elevation: 35 degrees
Camera azimuth: 50 degrees
13. Important Camera View Methods
| Method / Attribute | Purpose |
|---|---|
view_init() |
Sets the camera elevation, azimuth and optional roll. |
set_proj_type() |
Changes the projection type. |
set_box_aspect() |
Controls the relative dimensions of the 3D plotting box. |
set_xlim() |
Sets the X-axis viewing limits. |
set_ylim() |
Sets the Y-axis viewing limits. |
set_zlim() |
Sets the Z-axis viewing limits. |
savefig() |
Saves the selected 3D view to an image file. |
14. Common Mistakes
| Mistake | Explanation | Solution |
|---|---|---|
| Incorrect elevation | The surface may be difficult to inspect. | Adjust the elevation angle. |
| Incorrect azimuth | The desired side of the surface may not be visible. | Try different azimuth values. |
| Unsupported roll parameter | Older Matplotlib versions may not support roll. | Check the installed Matplotlib version. |
| Incorrect projection name | The projection type may not be recognized. | Use supported values such as "persp" or "ortho". |
| Assuming mouse interaction always works | Some backends display only static output. | Use an interactive backend. |
| Using deprecated camera distance | The dist attribute is deprecated. |
Prefer axis limits and box aspect adjustments. |
15. Best Practices
- Choose camera angles that reveal the important data features.
- Use elevation and azimuth together for better perspective.
- Use roll only when a rotated camera orientation is needed.
- Choose orthographic projection for parallel visual representation.
- Use perspective projection when depth perspective is useful.
- Adjust axis limits to focus on the relevant data range.
- Use interactive backends when users need to explore 3D plots.
- Save the plot after selecting the final camera view.
16. Practical Activity
3D Camera View Comparison Dashboard
Create a dashboard that compares the same 3D surface from different camera positions.
Requirements:
- Generate X and Y coordinate arrays using NumPy.
- Create a mesh grid using
np.meshgrid(). - Calculate Z values using a mathematical function.
- Create three 3D subplots.
- Set different elevation values for each subplot.
- Set different azimuth values for each subplot.
- Compare perspective and orthographic projection.
- Add titles and axis labels.
- Save the final Figure as a PNG image.
17. Practice Questions
- What is a camera view in 3D plotting?
- What is the purpose of
view_init()? - What is the difference between elevation and azimuth?
- What does the roll parameter control?
- How do you set the elevation to 45 degrees?
- What is orthographic projection?
- What is perspective projection?
- How can you change the 3D box aspect ratio?
- How do interactive backends help with 3D plots?
- How can you save a 3D plot with a selected camera angle?
Summary
Camera view settings control how a three-dimensional visualization
is displayed on a two-dimensional screen. Matplotlib provides
view_init() to customize elevation, azimuth and
supported camera roll settings.
Elevation controls the vertical viewing position, while azimuth changes the horizontal viewing direction. The roll parameter rotates the camera image around its viewing direction.
Matplotlib also supports perspective and orthographic projection. Axis limits, box aspect ratios and interactive backends help improve the presentation and exploration of 3D data.