Lesson 28 of 41
Matplotlib Foundations: Figures, Axes, Subplots & Styling
Overview & Learning Objectives
Matplotlib is the core plotting engine of the Python scientific ecosystem. While pyplot provides a state-machine interface mimicking MATLAB, production data engineering and analytics require the Object-Oriented (OO) API using explicit `Figure` and `Axes` objects. The OO API provides granular control over grid layouts, multi-axis overlays, spine visibilities, typography, and vector SVG/PDF rendering.
- Understand the Matplotlib Object-Oriented hierarchy: Canvas, Figure, Axes, and Artist elements.
- Generate multi-panel figure grids using `plt.subplots(nrows, ncols, figsize=(w, h))`.
- Format titles, axis labels, tick locators, legends, and export crisp high-DPI figures.
Industry Standard
Standard: Top-tier research institutions and financial publications like The Economist use Matplotlib OO API stylesheets to enforce strict corporate visual branding across all data charts.
Real-World Example: ScoopCraft Dark-Store Executive Multi-Panel Dashboard
ScoopCraft analytics builds a 2x2 multi-panel figure tracking store revenue, order volume, delivery times, and rating distributions.
| Panel Position | Plot Type | Primary Metric | Visual Goal |
|---|---|---|---|
| Axes [0, 0] | Line Chart | Daily Revenue Trend | Identify revenue trajectory across 30 days |
| Axes [0, 1] | Bar Chart | Volume by Dark Store | Compare regional fulfillment capacity |
| Axes [1, 0] | Histogram | Delivery Time (Min) | Assess SLA breach tail probability |
| Axes [1, 1] | Scatter Plot | Basket Size vs Tip | Examine tipping correlation with ticket size |
Syntax & Core Code Implementation
import matplotlib.pyplot as plt
# Object-Oriented 2x2 grid layout
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(14, 10), dpi=150)
fig.suptitle('ScoopCraft Dark-Store Performance Dashboard', fontsize=16, fontweight='bold')
# Panel 1: Revenue trend
axes[0, 0].plot(dates, revenue, color='#2563EB', linewidth=2.5, marker='o')
axes[0, 0].set_title('Daily Revenue Trend')
axes[0, 0].set_ylabel('Revenue ($)')
axes[0, 0].grid(True, linestyle='--', alpha=0.5)
# Save high-resolution publication output
plt.tight_layout()
fig.savefig('dashboard.png', dpi=300, bbox_inches='tight')
plt.show()
Parameters & Arguments Breakdown
fig, axes = plt.subplots(): Creates top-level Figure container and an array of individual Axes plotting canvases.figsize=(w, h): Dimensions of output figure in inches.dpi: Dots Per Inch resolution (150 for screens, 300 for print/presentations).bbox_inches="tight": Crops superfluous whitespace around figure boundaries during savefig.
Step-by-Step Implementation
- Instantiate Figure and Axes: Initialize canvas with `fig, ax = plt.subplots(figsize=(10, 6))`.
- Render Plot Artists: Call plotting methods directly on `ax` (e.g. `ax.plot()`, `ax.bar()`, `ax.scatter()`).
- Style and Export: Set labels via `ax.set_xlabel()`, format ticks, enable subtle grids, and export via `fig.savefig()`.
Common Mistakes & Limitations
- Mixing Pyplot stateful syntax (`plt.title()`) with OO syntax (`ax.set_title()`), leading to formatting applied to the wrong active subplot.
- Failing to call `plt.tight_layout()` or `layout="constrained"`, resulting in overlapping axis labels and clipped titles.
- Hardcoding low DPI exports (default 72-100 DPI) for executive slide presentations, producing blurry pixelated charts.
Keyboard Shortcuts (Jupyter & VS Code)
| Action | Windows | Mac |
|---|---|---|
| Re-run plotting cell in JupyterLab | Ctrl + Enter | Cmd + Enter |
Pro Tips & Modern Best Practices
- Use `ax.twinx()` to create a secondary y-axis sharing the same x-axis, perfect for plotting revenue (bars) alongside margin percentage (line).
- Turn off distracting chart borders with `ax.spines["top"].set_visible(False)` and `ax.spines["right"].set_visible(False)`.