Matplotlib Basics
The framework under every Python chart
Matplotlib's figure/axes model, object-oriented API, styling, subplots and savefig are the porcelain beneath every Python chart, including seaborn's.
What you will learn
- Use the figure/axes object model
- Build subplots and shared axes
- Export publication-quality figures
What is this?
Matplotlib is Python's foundational plotting library. The modern API is object-oriented: plt.subplots() returns a Figure and its Axes; every plot method is called on the Axes (ax.plot, ax.scatter, ax.set_xlabel). Subplots lay out several Axes; savefig exports. Seaborn wraps this machinery with statistical defaults.
Why do you need it?
- Every plotting library (seaborn, pandas.plot, plotly's layout) inherits matplotlib concepts.
- In a notebook you might use pyplot; in a dashboard you'll want figures saved programmatically via the object API.
- Subplots are how exploratory analysis shows many variables at once.
- Knowing the Axes methods prevents the wild 'why is my plot blank' confusion.
Mental model
A canvas (figure) with frames (axes) each holding a painting
Figure and Axes
One canvas can hold several frames — a figure with subplots. You paint on the frames, not the canvas; the axes is where lines, labels, legends and scales live.
How it works
- fig, ax = plt.subplots() builds a figure with one axes.
- ax.plot(x, y), ax.scatter, ax.bar, ax.hist draw on the axes.
- ax.set_title/set_xlabel/set_ylabel/legend(); fig.tight_layout() arranges.
- plt.subplots(1, 2) gives a grid of axes; sharex/sharey align them.
- fig.savefig('x.png', dpi=150, bbox_inches='tight') exports cleanly.
Anatomy of a figure.
Examples
Object-oriented small multiples
import matplotlib.pyplot as pltimport numpy as npx = np.linspace(0, 10, 100)fig, axes = plt.subplots(1, 2, figsize=(10, 3.5))axes[0].plot(x, np.sin(x), label="sin")axes[0].legend()axes[0].set_title("Trig")axes[1].bar(["a", "b", "c"], [3, 7, 2])axes[1].set_ylim(0, 8)fig.tight_layout()fig.savefig("figure.png", dpi=150)subplots hands back axes you draw on explicitly — the API the docs, seaborn and production code use. The canvas arranges itself with tight_layout and savefig writes the file for embedding.
In production
- A nightly report renders the same figure for each of 40 clients programmatically via a loop over shared code.
- A monitoring dashboard exports matplotlib PNGs and attaches them to Slack alerts.
- Seaborn under the hood draws its statistical plots on matplotlib Axes — style inheritance everywhere.
Best practices
- Use the object API (fig, ax) — not pyplot globals — in modules and functions.
- Call plt.style.use('seaborn-v0_8') or equivalent for consistent styling.
- Save with dpi=150+ and bbox_inches='tight' for clean exports.
Common mistakes
- plt.plot vs ax.plot mixing — stateful pyplot confusion in functions.
- Waiting to call plt.show() before savefig, or calling in subprocesses.
- Missing fig.tight_layout() → clipped labels.
Debugging tips
- Blank plot? You created a Figure but forgot Axes; or plt.show() before savefig.
- Overlapping labels → call fig.tight_layout() or constrain the axes.
- Matplotlibrc inconsistency across machines → pin style commands at the top of pipelines.
Interview checkpoint
Hands-on lab
- Create a figure with subplots via the OO API
- Draw lines, bars and histograms
- Export a clean image
Matplotlib from Blank to Dashboard-Ready
30 min · beginner
Quick quiz
In the modern matplotlib API, drawing happens on:
savefig must be called before plt.show() to capture the figure.