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 artifacts | You need interactive dashboards → Plotly, Bokeh |
| You are plotting training metrics from scratch | You want automatic experiment UI → TensorBoard, W&B |
| Another library (pandas, sklearn) returns an Axes object | You 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.
EDA Plots Every AI Engineer Uses
Histograms — Distribution Checks
Spot skew, outliers, and train/test distribution shift before they poison your model.
Scatter Plots — Relationships and Errors
Plot predicted vs actual values to diagnose systematic bias in regression models.
Heatmaps — Confusion Matrices
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.
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
- Short Answer: What is the difference between a Figure and an Axes? Answer: Figure is the canvas; Axes is one plot region on it.
- True/False:
plt.savefig()should be called on the Figure object for explicit control. Answer: True (recommended pattern). - Short Answer: Which plot best reveals train/val overfitting? Answer: Dual training and validation loss curves over epochs.
- Multiple Choice: Best tool for interactive dashboards: (a) Matplotlib, (b) Plotly, (c) both equally. Answer: (b).
- Short Answer: Which plot type checks skew, outliers, and train/test shift? Answer: Histogram (distribution plot).
- True/False: Scatter of predicted vs actual helps diagnose systematic bias in regression. Answer: True.
- Short Answer: How do you compare several feature distributions side by side? Answer: Use
plt.subplotsto create multiple Axes on one Figure. - Multiple Choice: Confusion matrices are typically shown as: (a) a heatmap, (b) a pie chart only, (c) audio, (d) a linked list. Answer: (a).
- True/False: Pretty plots are optional polish and not useful for debugging models. Answer: False—visualization is an engineering debugging tool.
- 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.
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.