← Master Index
Vol. 03 Module 3.3 Lecture

Matplotlib

AI & Data Libraries

How This Lesson Fits the Module

After Pandas helps you clean tabular data, you need to see it. Matplotlib is Python’s foundational plotting library—the layer beneath Seaborn, pandas .plot(), and many experiment-tracking dashboards.

Visual inspection catches label errors, distribution shift, and broken pipelines faster than any metric. Before training in Scikit-learn or PyTorch, plot your data.

Learning Objectives

By the end of this lesson, students should be able to:

  • Create line, scatter, histogram, and bar plots for ML diagnostics.
  • Understand Matplotlib’s Figure/Axes object model.
  • Visualize training curves, confusion patterns, and feature distributions.
  • Customize labels, legends, and styles for reproducible reports.
  • Choose Matplotlib versus higher-level libraries for a given task.
  • Export publication-quality figures for documentation and stakeholder review.

What Matplotlib Is—and When to Use It

Matplotlib is a low-level, highly customizable 2D plotting library. It gives fine-grained control over every axis, tick, and annotation—at the cost of verbosity compared to Seaborn or Plotly.

Use Matplotlib when…Consider alternatives when…
You need full control over figure layout and export (PNG/PDF/SVG)You want statistical plots in one line → Seaborn
You are embedding plots in papers, reports, or CI artifactsYou need interactive dashboards → Plotly, Bokeh
You are plotting training metrics from scratchYou want automatic experiment UI → TensorBoard, W&B
Another library (pandas, sklearn) returns an Axes objectYou only need quick EDA in a notebook → pandas .plot()

The Figure and Axes Model

Matplotlib separates the Figure (canvas) from Axes (individual plots). The object-oriented API is the professional default—it composes subplots cleanly and avoids global state bugs.

import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots(figsize=(8, 4)) epochs = np.arange(1, 21) train_loss = 1.2 * np.exp(-0.15 * epochs) + 0.05 * np.random.rand(20) val_loss = 1.1 * np.exp(-0.12 * epochs) + 0.12 ax.plot(epochs, train_loss, label="train") ax.plot(epochs, val_loss, label="validation") ax.set(xlabel="Epoch", ylabel="Loss", title="Training Curve") ax.legend() fig.tight_layout() fig.savefig("training_curve.png", dpi=150)

EDA Plots Every AI Engineer Uses

Histograms — Distribution Checks

Spot skew, outliers, and train/test distribution shift before they poison your model.

fig, ax = plt.subplots() ax.hist(df["monthly_spend"], bins=30, edgecolor="white") ax.set(xlabel="Monthly spend ($)", ylabel="Count", title="Spend distribution") plt.show()

Scatter Plots — Relationships and Errors

Plot predicted vs actual values to diagnose systematic bias in regression models.

fig, ax = plt.subplots() ax.scatter(y_true, y_pred, alpha=0.5, s=12) lims = [min(y_true.min(), y_pred.min()), max(y_true.max(), y_pred.max())] ax.plot(lims, lims, "--", color="gray", label="perfect prediction") ax.set(xlabel="Actual", ylabel="Predicted") ax.legend()

Heatmaps — Confusion Matrices

from sklearn.metrics import ConfusionMatrixDisplay fig, ax = plt.subplots() ConfusionMatrixDisplay.from_predictions(y_test, y_pred, ax=ax, cmap="Blues") ax.set_title("Validation confusion matrix")
ML Example — Detecting Overfitting Visually

When validation loss diverges upward while training loss keeps falling, you are overfitting. A simple dual-line plot saves hours of blind hyperparameter search. Log metrics every epoch and plot them—do not rely on the final accuracy number alone.

Subplots and Layout

Compare features side by side: class balance, per-feature distributions, and correlation structure.

fig, axes = plt.subplots(1, 3, figsize=(12, 3)) for ax, col in zip(axes, ["age", "income", "tenure"]): ax.hist(df[col], bins=20) ax.set_title(col) fig.suptitle("Feature distributions", y=1.02) fig.tight_layout()
Common Misconception: “Pretty plots are optional polish.”

Reality: Visualization is a debugging tool. Mislabeled axes, wrong scales, and cherry-picked epochs have shipped broken models to production. Treat plots as engineering artifacts, not decoration.

Advantages

  • Industry-standard, stable API
  • Fine-grained export control
  • Integrates with NumPy, Pandas, sklearn
  • Foundation for Seaborn and pandas plotting

Limitations

  • Verbose for common statistical plots
  • Default styles look dated without customization
  • Not interactive out of the box
  • Large figure counts slow notebook rendering

Knowledge Check

  1. Short Answer: What is the difference between a Figure and an Axes? Answer: Figure is the canvas; Axes is one plot region on it.
  2. True/False: plt.savefig() should be called on the Figure object for explicit control. Answer: True (recommended pattern).
  3. Short Answer: Which plot best reveals train/val overfitting? Answer: Dual training and validation loss curves over epochs.
  4. Multiple Choice: Best tool for interactive dashboards: (a) Matplotlib, (b) Plotly, (c) both equally. Answer: (b).
  5. Short Answer: Which plot type checks skew, outliers, and train/test shift? Answer: Histogram (distribution plot).
  6. True/False: Scatter of predicted vs actual helps diagnose systematic bias in regression. Answer: True.
  7. Short Answer: How do you compare several feature distributions side by side? Answer: Use plt.subplots to create multiple Axes on one Figure.
  8. Multiple Choice: Confusion matrices are typically shown as: (a) a heatmap, (b) a pie chart only, (c) audio, (d) a linked list. Answer: (a).
  9. True/False: Pretty plots are optional polish and not useful for debugging models. Answer: False—visualization is an engineering debugging tool.
  10. Short Answer: Why call fig.savefig(..., dpi=150)? Answer: Export a publication-quality figure at sufficient resolution for reports.

Key Takeaways

  • Matplotlib is the low-level plotting foundation for Python data science.
  • Use the Figure/Axes API for maintainable, composable plots.
  • Plot distributions, training curves, and error patterns before trusting metrics.
  • Export figures at sufficient DPI for reports and documentation.
  • Next: Scikit-learn for classical machine learning pipelines.
Trainer’s Guide

Hands-on idea: Train a simple classifier, then require students to submit three plots: class balance, learning curve, and confusion matrix—with labeled axes and a one-sentence interpretation each.

Recap: Matplotlib’s Figure/Axes API turns metrics into diagnostics; next, build classical ML pipelines in Scikit-learn.