Accuracy 0.9580 sounds strong until the confusion matrix shows three false positives and three false negatives, and until the calibration curve shows that the model is rarely wrong but almost always certain. The same 143 test rows produce a ROC AUC of 0.9952, an average precision of 0.9971 and a Brier score of 0.0267, and no single number among those tells you what the plots tell you in five seconds.
If you are new to the field, what machine learning is covers the basics first. This article teaches the five plots that answer the questions a score cannot: how the model improves with data, where its residuals go, which classes it confuses, how well it ranks, and whether its probabilities mean anything. It starts with what Matplotlib is and how a figure is built, then moves through each plot with the code that produced it, the numbers it revealed, and the mistakes that make a plot lie. The code runs on Windows 11 and Ubuntu 24.04.5 with Python 3.14.6 and 3.12.3, Matplotlib 3.11.2, NumPy 2.5.5 and scikit-learn 1.9.1, and every figure on the page is generated by the repository in one run.
The Short Answer
- Matplotlib draws figures; scikit-learn computes the numbers; pandas holds the table. The plotting is the last step, not the analysis.
- A figure has a
Figure, one or moreAxes, and the artists drawn on them. Use the object-oriented API and keep a reference to each Axes. - Set the style once with
rcParams, then every figure inherits it. - Five plots cover most model review: learning curve, residuals, confusion matrix, ROC and precision-recall, calibration.
- A plot without axis labels, units and the number of rows is decoration.
- Save vector SVG for the page and raster PNG for inspection; the PNG is not the deliverable.
What Is Matplotlib?
Matplotlib is a plotting library for Python and NumPy. It builds publication-quality figures from arrays, exposes an object-oriented API around Figure and Axes, and ships with a procedural pyplot interface that mimics MATLAB for quick interactive work.
It is the layer every other Python plotting tool sits on or borrows from. pandas will plot a DataFrame through it when asked, scikit-learn’s display objects draw with it, and seaborn wraps it. Learning the underlying object model once is what makes those wrappers predictable instead of magic.
The project began as an attempt to give Python the plotting workflow MATLAB users had, and the pyplot interface still carries that resemblance. The Matplotlib documentation itself notes that the state-machine style is convenient for exploration and discourages it for anything that has to be maintained, which is why this article uses the explicit object-oriented API throughout. The current documentation set is for 3.11.2, the version pinned here.
Where it sits: NumPy or pandas produces the numbers, Matplotlib draws them, and a backend writes the file. For a script the backend is Agg, which renders without a window and is what makes figures reproducible on a server. It is not a dashboard tool, it does not compute metrics, and it will not tell you which plot to draw.
python -m pip install matplotlib==3.11.2
The article starts with the anatomy of a figure and a shared style, then takes the five diagnostic plots in turn, and finishes with the choices that decide whether a figure survives being printed, embedded and read on a phone. The environment is covered in Python setup for machine learning, arrays in NumPy for machine learning, and tables in pandas for machine learning.
Anatomy of a Figure
Four objects explain almost everything that goes wrong with layout. A Figure is the canvas. An Axes is one plot inside it, with its own data coordinates, x-axis, y-axis and title. An Axis is the ruler for one dimension, holding ticks, tick labels and the scale. Everything visible, from a line to a text label, is an Artist attached to an Axes or a Figure.
import matplotlib.pyplot as plt
figure, axes = plt.subplots(figsize=(6.6, 3.96))
axes.plot([0, 1, 2], [0.6, 0.8, 0.9], color="#1A6FD4")
axes.set_xlabel("training rows")
axes.set_ylabel("accuracy")
figure.savefig("figure.svg", format="svg")
The explicit form is plt.subplots, which returns both objects. The pyplot state-machine form, plt.plot(...) followed by plt.savefig(...), keeps a hidden current figure and current Axes, so a function that plots without being told which Axes to draw on silently adds to whatever was current. That is the difference between a script that can build a five-panel report and one that draws all five panels on top of each other.
Two helpers settle most layout disputes. figure.tight_layout() recalculates spacing so labels are not clipped, and axes.grid(axis="y") adds horizontal reference lines without turning the plot into graph paper. This article’s figures use both.
Subplots and Shared Axes
A two-panel figure is a subplots call with a shape, not two separate figures. The ROC and precision-recall figure is one row and two columns:
figure, (left, right) = plt.subplots(1, 2)
left.plot(false_positive, true_positive, color=style.BLUE)
right.plot(recall, precision, color=style.GREEN)
figure.tight_layout()
Each Axes keeps its own labels, limits and legend, and sharey=True links two panels that measure the same quantity so the reader compares shapes rather than axis ranges. figure.suptitle gives the pair one title, and constrained_layout=True is the newer alternative to tight_layout when a colourbar or a long label is involved.
The plt.subplot(121) form does the same thing through the state machine and breaks as soon as a helper function plots without being given an Axes. Passing ax into every plotting function is the habit that makes multi-panel reports possible; the function signature def draw(ax, data) is the whole discipline.
For tables, pandas can draw through the same machinery: ax = frame.plot(kind="bar") returns the Axes, and styling it afterwards works exactly as above. Keep the returned Axes; the shortcut is convenient, not a different system.
One Style, Set Once
A house style is a few rcParams and a palette, applied before any figure exists. The file in the repository is 30 lines, and every plot inherits from it:
import matplotlib as mpl
BACKGROUND = "#F4F5F7"
PANEL = "#FFFFFF"
BLUE = "#1A6FD4"
GREEN = "#467F40"
AMBER = "#B8860B"
RED = "#B03030"
INK = "#1F2937"
def apply():
mpl.rcParams.update({
"figure.facecolor": BACKGROUND,
"axes.facecolor": PANEL,
"axes.edgecolor": "#9CA3AF",
"axes.spines.top": False,
"axes.spines.right": False,
"font.family": "sans-serif",
"font.size": 9,
"axes.labelsize": 9,
"axes.titlesize": 10,
"legend.frameon": False,
"grid.color": "#E5E7EB",
})
Three choices in that list do most of the visual work. Removing the top and right spines removes the box that makes a default Matplotlib figure look like a spreadsheet. A white panel on a light grey canvas separates the data from the page. A 9-point font at a 6.6 by 3.96 inch figure produces 660 by 396 pixels at 100 dpi; the article embeds the same vector drawing at 800 by 480, so it keeps the aspect ratio and scales without resampling.
Colour is the other half of the style, and it is where plots fail accessibility review. Blue and green are distinguishable to most colour-blind readers; blue and red are not, which is why the residual plot uses red only for the zero line and not for a data series. If two categories must be separated by colour alone, pick from a palette designed for it rather than the default cycle.
The Five Questions a Score Cannot Answer
| Question | Plot | What a bad result looks like |
|---|---|---|
| Does more data help, and is the model overfitting? | Learning curve | Training accuracy high and flat while validation stays far below |
| Is the model missing structure? | Residual plot | A curve, a fan or clusters instead of noise around zero |
| Which mistakes does it make? | Confusion matrix | The wrong class carrying most of the errors |
| How well does it rank, and at what threshold? | ROC and precision-recall | Curves close to the diagonal, or precision collapsing early |
| Do the probabilities mean what they say? | Calibration curve | Points far from the diagonal despite a good AUC |
A model can be excellent on any one of these and fail the next. The classifier in this article has a ROC AUC above 0.99 and a calibration curve that is nearly ideal, which is a genuinely easy problem, not a general property of logistic regression on tabular data.
Learning Curves
A learning curve answers whether the model needs more data or a different model. The code trains the same pipeline on increasing fractions of the training set, scores each fit with cross-validation, and plots the mean with a band of one standard deviation:
sizes, train_scores, validation_scores = learning_curve(
make_pipeline(StandardScaler(), LogisticRegression(max_iter=5000)),
features, target,
train_sizes=np.linspace(0.1, 1.0, 6),
cv=StratifiedKFold(n_splits=5, shuffle=True, random_state=0),
scoring="accuracy",
)
Read it in two directions. Validation accuracy climbs from 0.8734 at 45 training rows to 0.9789 at 455, so the first few hundred rows matter more than the last hundred. Training accuracy stays between 0.981 and 0.988 the whole way, and the gap between the two lines closes to 0.92 accuracy points at full size. A large persistent gap means variance and points to regularization, more data or a simpler model; both curves low and close means bias and points to better features.
The largest training size is 455 rather than the 426 training rows used by the other figures, and that is expected. learning_curve runs its own five-fold cross-validation over all 569 rows, so each fit trains on four fifths of them, 455 rows, and validates on the remaining 114. The other figures use one fixed 75/25 split: 426 training rows and 143 test rows.
The bands matter as much as the lines. At 45 rows the validation band is roughly six points wide, which is how much the estimate moves between folds. Two models compared at that size are compared inside their own noise.
Residual Plots
For a regression, the residuals are the part of the target the model did not explain. Plotting them against the prediction exposes structure that a single RMSE hides. The function fits a linear regression on the diabetes data and draws the residuals of the test rows:
def residual_figure():
bunch = load_diabetes()
train_x, test_x, train_y, test_y = train_test_split(
bunch.data, bunch.target, test_size=0.25, random_state=SEED
)
model = LinearRegression().fit(train_x, train_y)
predicted = model.predict(test_x)
residuals = test_y - predicted
figure, axes = plt.subplots()
axes.scatter(predicted, residuals, s=22, color=style.BLUE, alpha=0.75, edgecolors="none")
axes.axhline(0.0, color=style.RED, linewidth=1.0, linestyle="--")
axes.set_xlabel("predicted progression")
axes.set_ylabel("residual (actual minus predicted)")
axes.grid(axis="y")
axes.set_title("Residuals should look like noise, not a shape")
save(figure, "residuals")
return residuals
On the diabetes test rows the residuals have a mean of -3.721, a median absolute value of 40.469 and a maximum absolute value of 162.442. The mean near zero is expected from a model with an intercept; the spread is the interesting part. A curve in the cloud means the relationship is not linear, a fan that widens with the prediction means the error variance is not constant, and a few extreme points are the rows where the model is least trustworthy.
The plotting itself is four calls: a scatter, a horizontal line at zero, labels and a grid. The reason to draw it is not the code but the habit: every regression report should show where the errors live, because the aggregate statistic is an average over a shape nobody looked at.
Confusion Matrices
A confusion matrix is the only plot that shows which mistake a classifier makes. The function draws the counts as a single-hue image and writes each count in its cell:
def confusion_figure(model, test_x, test_y, bunch):
matrix = confusion_matrix(test_y, model.predict(test_x))
figure, axes = plt.subplots()
axes.imshow(matrix, cmap="Blues")
axes.set_xticks([0, 1], bunch.target_names)
axes.set_yticks([0, 1], bunch.target_names)
axes.set_xlabel("predicted")
axes.set_ylabel("actual")
for row in range(2):
for column in range(2):
value = int(matrix[row, column])
axes.text(
column, row, str(value), ha="center", va="center",
color="white" if value > matrix.max() / 2 else style.INK,
fontsize=12,
)
axes.set_title("The counts a single accuracy score hides")
save(figure, "confusion-matrix")
return matrix
On the 143 test rows of the breast cancer data it produces:
The model gets 50 malignant and 87 benign rows right, with 3 false positives and 3 false negatives. The accuracy is 0.9580, and the plot answers the question a clinician would ask next. The six errors split into equal counts but unequal rates: 3 of the 53 malignant tumours were missed (5.7%) and 3 of the 90 benign ones were flagged (3.3%). Equal counts on unequal classes are not symmetric errors, and a screening use would care most about the first rate. On an imbalanced problem the same plot would show a model that scores well by never predicting the minority class, which is exactly what the majority-class baseline does.
Two details make a confusion matrix readable. Annotate the counts in the cells, and use a single-hue colormap so intensity reads as magnitude. A rainbow colormap turns the matrix into a heat map with no order, and a matrix without counts forces the reader to estimate values from colour.
ROC and Precision-Recall
The ROC curve plots the true positive rate against the false positive rate at every threshold. The precision-recall curve plots precision against recall, and it is the more honest view when the positive class is rare. Both come from the same predicted probabilities, drawn side by side with one shared figure:
def roc_pr_figure(model, test_x, test_y):
probabilities = model.predict_proba(test_x)[:, 1]
false_positive, true_positive, _ = roc_curve(test_y, probabilities)
precision, recall, _ = precision_recall_curve(test_y, probabilities)
roc_area = auc(false_positive, true_positive)
average_precision = average_precision_score(test_y, probabilities)
figure, (left, right) = plt.subplots(1, 2)
left.plot(false_positive, true_positive, color=style.BLUE, linewidth=2, label=f"AUC {roc_area:.4f}")
left.plot([0, 1], [0, 1], color=style.GREY, linestyle="--", linewidth=1)
left.set_xlabel("false positive rate")
left.set_ylabel("true positive rate")
left.set_title("ROC curve")
left.legend(loc="lower right")
right.plot(recall, precision, color=style.GREEN, linewidth=2, label=f"AP {average_precision:.4f}")
right.set_xlabel("recall")
right.set_ylabel("precision")
right.set_title("Precision and recall")
right.legend(loc="lower left")
figure.tight_layout()
save(figure, "roc-and-precision-recall")
return roc_area, average_precision
The area under the ROC curve is 0.9952 and average precision is 0.9971 on the same rows. The two are close here because the classes are only mildly imbalanced, at 63 percent benign. On a dataset with one percent positives, a high ROC AUC can coexist with a precision-recall curve that collapses, because the false positive rate stays small while the number of false positives dwarfs the true ones.
The threshold is the decision that the curve makes visible. Each point on the curve is a different trade between the two errors, and the threshold table in logistic regression from scratch is a way of picking one on purpose rather than accepting the default 0.5. The diagonal on the ROC panel is what a random ranking would score, and it belongs on the plot as a reference.
Calibration
Ranking and probability are different claims. A model can rank well and still say 0.9 when the true frequency is 0.6. A calibration curve bins the predicted probabilities and plots the observed share of positives in each bin. Quantile bins put the same number of rows in each bin, which matters when most probabilities sit near 0 or 1:
def calibration_figure(model, test_x, test_y):
probabilities = model.predict_proba(test_x)[:, 1]
fraction_positive, mean_predicted = calibration_curve(
test_y, probabilities, n_bins=8, strategy="quantile"
)
brier = brier_score_loss(test_y, probabilities)
figure, axes = plt.subplots()
axes.plot([0, 1], [0, 1], color=style.GREY, linestyle="--", linewidth=1, label="perfect")
axes.plot(mean_predicted, fraction_positive, color=style.AMBER, marker="o", label="model")
axes.set_xlabel("predicted probability")
axes.set_ylabel("observed share positive")
axes.set_ylim(0.0, 1.05)
axes.set_xlim(0.0, 1.05)
axes.grid(axis="y")
axes.legend(loc="upper left")
axes.set_title(f"Calibration, Brier {brier:.4f}")
save(figure, "calibration")
return mean_predicted, fraction_positive, brier
The points sit close to the diagonal, and the Brier score is 0.0267, which combines calibration and sharpness into one number. Most rows land at probabilities near 1.0, which is why the top-right corner is crowded and the bins below 0.8 contain few rows. A calibration curve with empty regions is not a failure; it means the model rarely produces those probabilities, and the bins that do have rows are the ones to read.
Calibration matters whenever a probability is used as a number rather than a ranking: a risk score, a medical decision, a bidding system. It matters less when only the order is used, which is why the plot belongs after the ROC curve rather than instead of it.
Saving a Figure You Can Reuse
Every figure in the repository goes through one helper, so the format and the metadata are decided once:
def save(figure: plt.Figure, name: str) -> None:
style.FIGURES.mkdir(parents=True, exist_ok=True)
figure.savefig(style.FIGURES / f"{name}.svg", format="svg", metadata={"Date": None})
figure.savefig(style.FIGURES / f"{name}.png", dpi=100)
plt.close(figure)
metadata={"Date": None} removes the creation timestamp that Matplotlib otherwise writes into every SVG. Without it, regenerating an unchanged figure produces a different file, and version control shows a change on every run. The SVG is the version to publish, because it scales without resampling; the PNG at 100 dpi is for a quick look and for places that cannot show SVG. plt.close(figure) matters in a script that draws many figures, because pyplot keeps every open figure in memory until it is closed.
Common Mistakes
A truncated y-axis exaggerates a difference. Starting an axis at 95 percent makes a one-point change look like a cliff, and it is the most common misleading choice in a results post; start at zero for counts and bars, and say why when a line chart needs a narrower range.
A plot without units, row counts or labels is unreadable six months later. Every axis needs a quantity and, where it applies, a unit; every caption needs the number of rows behind it.
Line plots for unordered categories imply a progression that does not exist. Categories get bars or dots; time series get lines.
Rainbow colormaps for ordered data destroy the reader’s ability to compare magnitudes, and they are hostile to colour-blind readers. Use one hue, darker for more.
The default style is not neutral. It is a set of choices, and leaving it means every figure looks like every other Matplotlib figure without a reason.
More ink is not more information. Grids on both axes, a legend for two series that could be labelled directly, and a title that repeats the caption all cost attention.
A Checklist for a Diagnostic Figure
- State the question the figure answers in its title, as a sentence rather than a topic.
- Label both axes with the quantity and the unit.
- Put the row count and the split in the caption.
- Show a reference line where one exists: chance, zero, perfect calibration.
- Use one hue for magnitude, two distinguishable hues for categories.
- Start bars and counts at zero; justify any other range on the figure.
- Include the metric that the plot supports, computed from the same rows.
- Save SVG with the timestamp removed (
metadata={"Date": None}), and PNG at the exact embed size. - Look at the rendered figure at 260 pixels wide before publishing.
Key Takeaways
- A figure has a Figure, Axes and artists; keep a reference to each Axes instead of relying on the current one.
- Set
rcParamsonce so the palette and spacing are inherited, not repeated. - Five plots cover model review: learning curve, residuals, confusion matrix, ROC and precision-recall, calibration.
- Read a learning curve in two directions: the level of validation and the gap to training.
- A confusion matrix shows which error the model makes; an accuracy score does not.
- ROC AUC and average precision answer different questions, and the second is more honest under severe imbalance.
- A good ranking does not imply calibrated probabilities; the calibration curve and Brier score do.
- Save vector, remove the timestamp, and check the figure at thumbnail size.
Source Code and Tests
All programs on this page are in the python/matplotlib-for-machine-learning directory of the MYCPLUS Python examples repository, with the style module, the diagnostics script and all five figures.
Build and test:
python -m pip install -r requirements.txt
python diagnostics.py
python -m unittest discover -s tests -v
The evaluation follows the series’ testing protocol for machine learning code. The 9 tests check that the house style is applied, that the confusion matrix sums to the test rows, that the ranking scores stay above 0.98, that the calibration arrays are probabilities, that a learning curve is monotone in training size, and that a saved figure produces both an SVG and a PNG.
What I Verified
| Check | Windows 11 | Ubuntu 24.04.5 (WSL 2) |
|---|---|---|
| Environment | Python 3.14.6, Matplotlib 3.11.2, NumPy 2.5.5, scikit-learn 1.9.1 | Python 3.12.3, same library versions |
| Diagnostics output | Accuracy 0.9580, AUC 0.9952, AP 0.9971, Brier 0.0267 | Identical, line for line |
| Confusion matrix | 3 false positives, 3 false negatives | Identical |
| Learning curve | 0.8734 at 45 rows to 0.9789 at 455 | Identical numbers |
| Five figures | SVG and PNG written, rendered with cairosvg | Rendered and compared |
| 9 unit tests | Pass | Pass |
Not covered: interactive backends, 3D plots, geographic plots, animation, and other Matplotlib versions. The figures are generated from scikit-learn’s bundled datasets, not from a production model.



