Master Matplotlib From Scratch

Learn Matplotlib fundamentals, figure anatomy, basic plotting, chart customization, subplots, statistical visualizations, color mapping, annotations, 3D plotting, animations, and interactive visualizations through structured practical lessons.

COURSE SYLLABUS
1. Introduction & Environment Setup
What is Matplotlib? Installation Environment Setup Imports and Conventions
2. Core Figure Anatomy & Structures
Figure vs Axes Creating Canvas Dimensions and Resolution Saving Visuals
3. Basic Plotting
Line Plots Scatter Plots Bar Charts Histograms
4. Basic Visual Formatting & Labels
Titles and Labels Text Customization Legends Grid Lines
5. Advanced Plot Customization
Format Strings Line and Marker Styling Color Systems Transparency
6. Axis Control, Ticks & Limits
Axis Limits Custom Ticks Tick Labels Axis Scaling
7. Multi-Plot Layouts & Subplots
Basic Subplots Indexing Subplots Layout Tuning Advanced Grids
8. Advanced Statistical & Data-Specific Plots
Pie Charts Box and Whisker Plots Violin Plots Error Bars
9. Color Mapping & 2D Data Visualizations
Colormaps Heatmaps and Images Colorbars Contour Plots
10. Annotations & Shapes
Basic Text Smart Annotations Drawing Shapes Shading Areas
11. Customizing Styles & Themes
Built-in Styles Custom Style Sheets Global Configurations
12. Object-Oriented API vs Pyplot
Pyplot vs Object-Oriented API Transitioning Methods Dual Axis Plots
13. Deep Integration with Pandas & Seaborn
Pandas Plotting Backend Seaborn Overlays Passing Axes
14. 3D Plotting
3D Setup 3D Lines and Scatter Surface and Wireframes Camera View
15. Dynamic & Live Plots
Interactive Mode Animation Module Real-time Updates Exporting Animations
16. Performance Optimization & Interactive Backends
Plotting Speed Interactive Backends Event Handling

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.
X Y Z Camera direction Elevation Azimuth Conceptual view of camera direction and coordinate axes

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.
Tip: A low elevation gives a more side-oriented view, while a higher elevation gives a more top-oriented view.

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.

Version Note: The 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.

Important: The 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.
Note: Interactive mouse rotation depends on the Matplotlib backend and execution environment. A static image output does not provide interactive camera controls.

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:

  1. Generate X and Y coordinate arrays using NumPy.
  2. Create a mesh grid using np.meshgrid().
  3. Calculate Z values using a mathematical function.
  4. Create three 3D subplots.
  5. Set different elevation values for each subplot.
  6. Set different azimuth values for each subplot.
  7. Compare perspective and orthographic projection.
  8. Add titles and axis labels.
  9. Save the final Figure as a PNG image.

17. Practice Questions

  1. What is a camera view in 3D plotting?
  2. What is the purpose of view_init()?
  3. What is the difference between elevation and azimuth?
  4. What does the roll parameter control?
  5. How do you set the elevation to 45 degrees?
  6. What is orthographic projection?
  7. What is perspective projection?
  8. How can you change the 3D box aspect ratio?
  9. How do interactive backends help with 3D plots?
  10. 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.