Visualization
Beginner 14 min read Visualization

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.

pyplotfigureaxessubplotsavefigstyle
Before we start

What you will learn

  • Use the figure/axes object model
  • Build subplots and shared axes
  • Export publication-quality figures
Introduction

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.

Motivation

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.
Think about it

Mental model

Imagine

A canvas (figure) with frames (axes) each holding a painting

Think of

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.

Mechanics

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.

Figure
Axes
Artist
Decor
Export
Hands-on

Examples

Object-oriented small multiples

Object-oriented small multiples
import matplotlib.pyplot as plt
import numpy as np
x = 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.

Real world

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.
Guidelines

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.
Watch out

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.
When things break

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.
Interviews

Interview checkpoint

Practice

Hands-on lab

Matplotlib from Blank to Dashboard-Ready
30 min · beginner
In progress
Objectives
  • 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

0/5 steps
0%
sandbox · Linux sandbox
$
Try these commands
Test yourself

Quick quiz

0/2
1

In the modern matplotlib API, drawing happens on:

2

savefig must be called before plt.show() to capture the figure.

Go deeper

Official documentation