Search Knowledge

© 2026 LIBREUNI PROJECT

Python for Scientific Computing / Data Visualization Deep Dive

Matplotlib: The Figure and Axes Architecture

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.

Code
skinparam componentStyle rectangle

package "Figure" as Fig {
component "Axes" as AX1
}

component "Axis" as Axis
component "Title" as Title
component "Legend" as Legend
component "Ticks" as Ticks
component "Grid" as Grid
component "Lines" as Lines

AX1 *-- Axis
AX1 *-- Title
AX1 *-- Legend
AX1 *-- Ticks
AX1 *-- Grid
AX1 *-- Lines

note bottom of AX1: "A Figure can contain\nmultiple Axes (subplots)."
FigureAxesAxisTitleLegendTicksGridLines"A Figure can containmultiple Axes (subplots)."

The Figure vs. The Axes

  1. Figure: The top-level container. Think of it as the physical page or empty window.
  2. Axes: A “subplot.” It is the area where the data is actually plotted. Most operations (setting titles, labels, grids) happen on an Axes object.

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.

ArtistPurpose
Line2DRepresents the data lines.
TextUsed for titles, labels, and annotations.
AxisManages the scale, limits, and tick locations.
PatchUsed 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.