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 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-axis Y-axis Z-axis Origin (0, 0, 0) Three coordinate directions in a 3D plotting area

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.
Note: In modern Matplotlib, using 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.
  • 111 represents 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.
Best Practice: Use 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.
Important: A 3D plotting area must be created with 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:

  1. Create a list of student study hours.
  2. Create a list of attendance percentages.
  3. Create a list of examination scores.
  4. Create a 3D Axes object using Matplotlib.
  5. Plot the values using ax.scatter().
  6. Set the X-axis label to Study Hours.
  7. Set the Y-axis label to Attendance.
  8. Set the Z-axis label to Exam Score.
  9. Add a chart title and customize the viewing angle.

13. Practice Questions

  1. What is 3D plotting?
  2. What is the purpose of the mplot3d toolkit?
  3. How do you create a 3D Axes object in Matplotlib?
  4. What does projection="3d" do?
  5. What are X, Y and Z axes?
  6. How do you create a 3D scatter plot?
  7. What is the purpose of view_init()?
  8. How do you set limits for the Z-axis?
  9. What is the difference between 2D and 3D plotting?
  10. 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.