Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 62/ 160
04. Data Visualization & BI

Matplotlib Fundamentals & Subplots

Create publication-ready plots with figure/axes APIs, labels, legends, and subplots.

BeginnerFigure/Axes · Subplots3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Matplotlib gives you a blank page (the figure) with boxes on it (the axes); you draw your charts into those boxes and add titles and labels.

Think of it like…

A Figure is a sheet of graph paper pinned to a board, and each Axes is a framed chart drawn on it. You choose the board size, arrange the frames and then draw into each frame by name instead of into "whichever one is current".

Where you’ve seen it

A data scientist builds a 2 × 2 dashboard figure for a weekly model report: top-left the daily error rate line, top-right a histogram of residuals, bottom-left predicted versus actual scatter, bottom-right feature importance bars. The figure is created with plt.subplots(2, 2, figsize=(10, 6), constrained_layout=True); the two time-based panels share the x axis with sharex; labels, units and titles are set on each Axes; and the figure is saved with fig.savefig("report.png", dpi=200, bbox_inches="tight"). At 10 × 6 inches and 200 dpi the output is 2,000 × 1,200 pixels, sharp in a slide deck. A loop that generated 60 per-customer figures previously leaked memory because figures were never closed; adding plt.close(fig) fixed it.

Words you’ll hear

Figure
The top-level container: size, DPI and all Axes.
Axes
One plot area with its own x/y axes, ticks, labels and data artists.
Object-oriented API
Calling methods on Figure and Axes objects explicitly instead of relying on the current axes.
Layout manager
constrained_layout or tight_layout, which prevent overlapping labels.

Visual diagram

Loading interactive diagram

Theory & deep dive

The anatomy and the object-oriented workflow

A Figure owns the canvas size (figsize in inches) and resolution (dpi); each Axes owns the data coordinates, the axis objects (ticks, tick labels, scales) and the artists drawn on it (lines, collections, patches, text). Create both with fig, ax = plt.subplots(); for grids use fig, axs = plt.subplots(nrows, ncols), where axs is a 2D NumPy array of Axes (a single Axes when 1 × 1, a 1D array for one row or column, controlled by squeeze). Draw with methods: ax.plot(x, y, label="..."), ax.scatter, ax.bar, ax.hist, ax.errorbar, ax.fill_between, then style with ax.set_title, ax.set_xlabel, ax.set_ylabel, ax.set_xlim, ax.legend, ax.grid.

Pandas integrates directly: df.plot(ax=ax, x="date", y="sales") draws into a chosen Axes, which is the clean way to mix pandas and Matplotlib. Use sharex=True or sharey=True so panels align, gridspec_kw={"height_ratios": [3, 1]} for uneven panels, and fig.suptitle for an overall title. Colours come from the style's cycle; set a style with plt.style.use("seaborn-v0_8-whitegrid") or define your own rcParams (font size, line width) once for consistency across a project.

A two-panel figure

fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 6), sharex=True, constrained_layout=True) then ax1.plot(df.date, df.sales) and ax2.bar(df.date, df.orders); label both y axes, and set the x label only on ax2.

Key takeaway: Create Figure and Axes explicitly, draw with Axes methods, and let pandas plot into a given Axes.

Layout, export and common pitfalls

Overlapping labels are the most common flaw. constrained_layout=True (set when creating the figure) negotiates spacing between Axes, colourbars and legends and is generally more reliable than fig.tight_layout(). Place legends outside crowded plots with ax.legend(loc="upper left", bbox_to_anchor=(1.01, 1)), rotate crowded tick labels, format dates with matplotlib.dates locators and formatters, and use ax.annotate for key events. For exact sizes, remember that pixels = inches × dpi: a figure meant for a 6.5-inch-wide document column at 300 dpi should be 6.5 inches wide and export at 300 dpi (1,950 pixels).

Save with fig.savefig(path, dpi=..., bbox_inches="tight"); use vector formats (.svg, .pdf) for print and .png for slides and web, and set transparent=True only if needed. Pitfalls: mixing plt. calls with ax. calls so labels land on the wrong panel; creating figures in a loop without plt.close(fig) (Matplotlib warns after 20 open figures and memory grows); calling plt.show() in scripts and notebooks inconsistently; and reusing a global style that changes later plots unexpectedly (use with plt.style.context(...)). For interactive exploration, use %matplotlib widget in notebooks or a library such as Plotly when hover is needed.

Close figures in loops

for cid, g in df.groupby("customer"): fig, ax = plt.subplots(); g.plot(ax=ax); fig.savefig(f"{cid}.png"); plt.close(fig) Without the close, 60 figures stay in memory and Matplotlib prints a warning after 20.

Key takeaway: Use constrained layout, choose size and dpi deliberately, export in the right format and close figures in loops.

How it works, step by step

Step 1 of 4
Analyst

1. Create the Figure and Axes

Call subplots with the grid shape, figsize and constrained_layout; decide which panels share axes.

plt.subplots(2, 2, figsize=(10, 6), sharex=...)
Key numbers at this step
Size
inches × dpi = pixels

When to use it & trade-offs

What it is

Matplotlib is Python's foundational plotting library, and its core model is a Figure (the canvas) that holds one or more Axes (individual plots, each with its own x and y axis, ticks, labels and artists). The recommended style is the object-oriented API: fig, ax = plt.subplots() and then ax.plot(...), ax.set_xlabel(...), ax.legend(). The older pyplot state-machine style (plt.plot) draws on an implicit current axes, which is fine for quick looks but becomes confusing with several panels. Subplots, shared axes, layout managers and exporting at the right size and DPI turn a scratch plot into a publication-ready figure.

Why it matters: Most Python visualisation libraries (pandas plotting, seaborn, many others) sit on Matplotlib, so understanding Figure and Axes lets you customise anything they produce. Reports and papers need exact sizes, consistent fonts, aligned panels and high-resolution exports; interviewers and teammates expect an analyst to build multi-panel figures without fighting global state.

When to reach for it

  • Report and paper figures with exact size and dpi
  • Multi-panel diagnostics for models
  • Customising seaborn and pandas plots

When to avoid or be careful

  • Using plt.plot repeatedly across several subplots
  • Generating many figures without closing them
  • Relying on default font sizes for slides

Matplotlib APIs and neighbours

Object-oriented API (Figure and Axes)
Best for: Multi-panel, reusable and production figures

Strengths: Explicit control; no hidden state.

Watch out: Slightly more verbose.

pyplot state machine (plt.plot)
Best for: Quick single plots in a notebook

Strengths: Short and familiar.

Watch out: Implicit current axes cause mistakes with subplots.

Seaborn or Plotly on top
Best for: Statistical defaults or interactivity

Strengths: Higher-level, attractive output.

Watch out: Customisation still needs Matplotlib knowledge or its own API.

Interview signals & numbers to know

When this topic comes up

  • “How do I make a 2 by 2 figure?”
  • “Labels overlap”
  • “Figure vs Axes”
  • constrained_layout
  • Memory growth when saving many plots

Benchmarks & rules of thumb

inches × dpi -
pixel size: 10 × 6 at 200 dpi = 2,000 × 1,200
20 -
open figures before Matplotlib warns
300 dpi -
common print resolution

Common mistakes & follow-ups

Common interview mistakes

  • Calling plt.xlabel after switching axes and labelling the wrong panel.
  • Saving a PNG for print instead of a vector format.
  • Forgetting that subplots returns a 2D array for grids and a single Axes for 1 × 1.

Likely interviewer follow-ups

  • What is the difference between a Figure and an Axes?
  • How do you avoid overlapping labels in subplots?
  • How would you generate 100 plots in a loop safely?
Interview tip: Show the Figure and Axes split and the savefig dpi arithmetic. It signals you can control output, not just call plot.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Matplotlib Fundamentals & Subplots with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Principles of Visual Perception & Chart Selection
Next topic
Statistical Plotting with Seaborn