Python
Topic 20 · Python for data · ⏱ about 6 h

Plotting with Matplotlib & seaborn

Figures and axes, the five chart types you need, labels that make charts readable, seaborn for statistical plots, and the standard ML evaluation plots.

Show:
In this topic
Beginner

Why ML engineers plot everything

Charts are how you find problems (a spike of impossible ages, a feature that leaks, a model that only fails at weekends) and how you explain results to people who will never read a table. Every stage of an ML project produces plots: exploring the data, checking features, comparing models, reporting to stakeholders, monitoring in production.

Python has two libraries you will use constantly. Matplotlib is the foundation: it can draw anything, and you control every detail. seaborn sits on top of it and draws common statistical charts from a pandas DataFrame in one line (distributions, group comparisons, correlation heatmaps), with good defaults. pandas also has a quick df.plot(), and scikit-learn draws evaluation plots onto Matplotlib axes.

Beginner

Figures, axes and the object-oriented style

A figure is the whole image; it contains one or more axes, each a single chart with its own x-axis, y-axis, title and data. Create both at once with plt.subplots, then call methods on each axes. This "object-oriented" style is clearer than calling plt.plot repeatedly, and it is what you need as soon as a figure has more than one chart.

import matplotlib.pyplot as plt fig, axes = plt.subplots(1, 2, figsize=(10, 4)) # 1 row, 2 columns of charts ax = axes[0] ax.plot(months, rate, marker="o", label="no-show rate") # line ax.set_title("No-show rate by month") ax.set_xlabel("month"); ax.set_ylabel("no-show rate") ax.legend() axes[1].hist(df["lead_days"], bins=30) # histogram axes[1].set_xlabel("lead days") fig.tight_layout() # stop labels overlapping fig.savefig("report.png", dpi=150) plt.show()

The methods you will use most: ax.plot (lines), ax.scatter, ax.bar/ax.barh, ax.hist, ax.boxplot, ax.imshow (images and matrices), plus ax.axhline/ax.axvline for reference lines, ax.bar_label for values on bars, ax.set_xlim/set_ylim, and ax.annotate for an arrow and a note.

Try it

Try it: choose the right chart

Pick the question you want the chart to answer. You will see the chart type that answers it, a typical mistake to avoid, and the Matplotlib and seaborn code.

Interactive: this part runs in your browser.

Try it

Code example: your first figure

A worked example: read it step by step (every part is explained), then run it and experiment.

Interactive: this part runs in your browser.

Beginner

Charts people can read

  • One message per chart, and say it in the title: "Bookings made far ahead are missed more often" beats "Bar chart of rate".
  • Label axes with units (days, $, %). Start bar charts at zero; line charts may zoom in, but say so.
  • Sort categories by value unless they have a natural order (days, age groups).
  • Add a reference: the overall average, a target, last year.
  • Colour with purpose: highlight one thing in a strong colour and grey out the rest; use colour-blind-safe palettes (Matplotlib's default tab10, viridis, seaborn's colorblind); use a diverging palette centred at zero for values that can be negative, like correlations.
  • Show uncertainty when groups are small: error bars or confidence intervals.
  • Avoid 3-D charts, dual y-axes and pie charts with many slices: they distort comparisons.
Try it

Code example: comparison and relationship charts

A worked example: read it step by step (every part is explained), then run it and experiment.

Interactive: this part runs in your browser.

Beginner

seaborn: statistical charts in one line

seaborn takes a DataFrame and column names, groups and aggregates for you, and draws onto a Matplotlib axes (pass ax= to place it). The functions you will reach for:

import seaborn as sns sns.set_theme(style="whitegrid", palette="colorblind") sns.histplot(data=df, x="lead_days", hue="no_show", bins=30) # distribution, split by outcome sns.boxplot(data=df, x="clinic", y="lead_days") # compare distributions across groups sns.barplot(data=df, x="clinic", y="no_show", errorbar=("ci", 95)) # mean per group with a 95% CI sns.scatterplot(data=df, x="age", y="lead_days", hue="no_show", alpha=.5) sns.heatmap(df[num_cols].corr(), annot=True, fmt=".2f", cmap="vlag", center=0) sns.pairplot(df[num_cols + ["no_show"]], hue="no_show") # every pair of features at once

Note barplot on a 0/1 column computes the rate per group and its confidence interval automatically. seaborn returns the Matplotlib axes, so you can still add titles, reference lines and annotations with the usual methods. (In this course's browser Python, seaborn is downloaded from the Python Package Index the first time you use it, which needs an internet connection.)

Try it

Code example: a heatmap and a box plot with seaborn

A worked example: read it step by step (every part is explained), then run it and experiment.

Interactive: this part runs in your browser.

Advanced

The standard ML plots

A short list worth knowing by heart, because reviewers expect them:

  • Learning curves (training and validation loss per epoch or per training size): diagnose over- and underfitting.
  • Confusion matrix at the chosen threshold, and ROC and precision–recall curves across thresholds (scikit-learn: ConfusionMatrixDisplay, RocCurveDisplay, PrecisionRecallDisplay).
  • Calibration curve: are predicted probabilities right on average? (CalibrationDisplay)
  • Residual plots for regression: errors against predictions should look like random noise (PredictionErrorDisplay).
  • Feature importance and partial dependence (PartialDependenceDisplay).
  • Metric per group with confidence intervals: the fairness view.
  • Drift over time: a feature's distribution or PSI by week.
Code

Code: an evaluation dashboard in one figure

Four standard plots for a classifier, using scikit-learn's display classes on a 2 × 2 grid.

Python · Matplotlib + scikit-learn
import matplotlib.pyplot as plt
from sklearn.metrics import ConfusionMatrixDisplay, RocCurveDisplay, PrecisionRecallDisplay
from sklearn.calibration import CalibrationDisplay

p = model.predict_proba(X_val)[:, 1]
fig, ax = plt.subplots(2, 2, figsize=(10, 8))
ConfusionMatrixDisplay.from_predictions(y_val, p >= 0.3, display_labels=["attended", "no-show"], ax=ax[0, 0], colorbar=False)
RocCurveDisplay.from_predictions(y_val, p, ax=ax[0, 1]);  ax[0, 1].plot([0, 1], [0, 1], "k--", lw=1)
PrecisionRecallDisplay.from_predictions(y_val, p, ax=ax[1, 0]);  ax[1, 0].axhline(y_val.mean(), ls="--", color="grey")
CalibrationDisplay.from_predictions(y_val, p, n_bins=10, ax=ax[1, 1])
for a, t in zip(ax.flat, ["Confusion matrix @ 0.3", "ROC", "Precision–recall", "Calibration"]):
    a.set_title(t)
fig.tight_layout(); fig.savefig("evaluation.png", dpi=150)
Open in playground ↗
Before it runs, the course trains a quick logistic-regression model on the synthetic clinic appointments, so model, X_val and y_val exist.
Try it

Cheat sheet: Matplotlib & seaborn

The commands you will use most, on one screen. Come back to it while you work.

Interactive: this part runs in your browser.

Check yourself

Quiz

1. In fig, axes = plt.subplots(2, 3), how many charts can you draw?

2. Which chart best shows the distribution of one numeric feature?

3. You want to compare no-show rates across 12 clinics. The clearest chart is…

4. What does sns.barplot(data=df, x="clinic", y="no_show") show for a 0/1 column?

5. Which palette suits a correlation heatmap (values from −1 to 1)?

Go deeper

📚 Further reading

Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.

Ready