Beyond “Simple” Plotting
Many beginners start with plt.plot() and quickly get frustrated when they can’t control the details of their figure. To master Matplotlib, you must understand its Object-Oriented (OO) Architecture.
The Hierarchy of a Plot
A Matplotlib plot is not just a bunch of lines; it’s a hierarchy of objects called Artists.
The Figure vs. The Axes
- Figure: The top-level container. Think of it as the physical page or empty window.
- Axes: A “subplot.” It is the area where the data is actually plotted. Most operations (setting titles, labels, grids) happen on an
Axesobject.
Creating Subplots the Pro Way
The most common way to start a plot is with plt.subplots().
python
1
2import matplotlib.pyplot as plt
3import numpy as np
4
5# Create figure and axes
6fig, ax = plt.subplots(figsize=(10, 5))
7
8# Generate data
9x = np.linspace(0, 10, 100)
10y = np.sin(x)
11
12# Plotting on the Axes object
13ax.plot(x, y, label='Sine Wave', color='#2563eb', linewidth=2.5)
14
15# Setting attributes on the Axes object
16ax.set_title('Hierarchical Plot Construction', fontsize=16, fontweight='bold')
17ax.set_xlabel('Time (s)')
18ax.set_ylabel('Amplitude')
19ax.grid(True, linestyle='--', alpha=0.6)
20ax.legend()
21
22plt.show()
23
Anatomy of a Figure
Each element you see—the title, the tick labels, the lines—is a separate Artist object that can be customized.
| Artist | Purpose |
|---|---|
| Line2D | Represents the data lines. |
| Text | Used for titles, labels, and annotations. |
| Axis | Manages the scale, limits, and tick locations. |
| Patch | Used for boxes, circles, and bars. |
Multiple Subplots
The power of the OO API becomes clear when you have multiple plots in a single figure.
python
1
2import matplotlib.pyplot as plt
3import numpy as np
4
5x = np.linspace(0, 10, 100)
6
7# Create a 2x1 grid of plots
8fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 8), sharex=True)
9
10ax1.plot(x, np.sin(x), 'r')
11ax1.set_title('Sine')
12
13ax2.plot(x, np.cos(x), 'b')
14ax2.set_title('Cosine')
15
16# Automatically adjust spacing
17plt.tight_layout()
18plt.show()
19
In the next lesson, we will explore how to style these components to create publication-quality figures.