Display Objects and Visualizations in scikit-learn

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

scikit-learn does not ship a general plotting library. It ships a small, consistent API of Display classes that turn the numbers a model evaluation produces (ROC points, a confusion matrix, partial-dependence curves) into Matplotlib figures, and that keep those numbers so a figure can be redrawn, restyled or combined with another one without recomputing anything. This page explains that API, lists every Display class, shows a complete example for each of them and covers the traps (the positive class, unshuffled data, and the functions that older tutorials still call). It targets scikit-learn 1.9 (1.9.1 at the time of writing) with Matplotlib 3.11 and NumPy 2.5, and was checked in October 2026. Examples target Python 3.13 or 3.14 and were run on Python 3.13. Every example was run with Python 3.13, scikit-learn 1.9.1, Matplotlib 3.11.2 and pandas 3.1.0; the printed output is the real output. The examples save figures with fig.savefig(...) so they also work in a script or on a server without a display; in a notebook the figure appears automatically.

Matplotlib itself is introduced in Data Visualization; the metrics behind these plots are explained in Metrics & Scoring.

The Display API

Every Display class follows the same pattern, summarised by the official user guide:

  • A class method creates and draws the display. from_estimator(estimator, X, y) takes a fitted estimator and the data, asks the estimator for what it needs (predict_proba, decision_function, predict) and draws. from_predictions(y_true, y_pred) takes values you already have and therefore avoids recomputing predictions. from_cv_results(cv_results, X, y) draws one curve per fold from the output of cross_validate.

  • The returned Display object stores the computed values as attributes (fpr, tpr and roc_auc for RocCurveDisplay; confusion_matrix for ConfusionMatrixDisplay; train_scores and test_scores for LearningCurveDisplay) together with the Matplotlib objects it created: ax_ (the Axes, or an array of Axes) and figure_.

  • A plot method draws the stored values again. It accepts an ax argument, so the same display can be drawn on an existing Axes, on several Axes, or with different styling, with no new computation.

  • Constructing a Display directly with its __init__ is possible but not recommended; use the class methods.

flowchart LR est["fitted estimator + X, y"] -->|from_estimator| disp["Display object<br/>stored values, ax_, figure_"] pred["y_true + y_pred or scores"] -->|from_predictions| disp cvr["cross_validate output"] -->|from_cv_results| disp disp -->|plot with ax=...| fig["Matplotlib Axes"] disp -->|attributes| num["fpr, tpr, confusion_matrix, ..."]

The classes in scikit-learn 1.9

Class and module Constructors Draws Key attributes

metrics.RocCurveDisplay

from_estimator, from_predictions, from_cv_results

ROC curve, optional chance level

fpr, tpr, roc_auc

metrics.PrecisionRecallDisplay

from_estimator, from_predictions, from_cv_results (new in 1.9)

Precision-recall curve

precision, recall, average_precision

metrics.DetCurveDisplay

from_estimator, from_predictions

Detection error tradeoff curve (false-negative rate against false-positive rate)

fpr, fnr

metrics.ConfusionMatrixDisplay

from_estimator, from_predictions

Confusion matrix as a heat map

confusion_matrix, display_labels

metrics.PredictionErrorDisplay

from_estimator, from_predictions

Regression: actual against predicted, or residuals against predicted

y_true, y_pred

calibration.CalibrationDisplay

from_estimator, from_predictions

Reliability diagram

prob_true, prob_pred

model_selection.LearningCurveDisplay

from_estimator

Score against training-set size

train_sizes, train_scores, test_scores

model_selection.ValidationCurveDisplay

from_estimator

Score against one hyperparameter

param_name, param_range, train_scores, test_scores

inspection.PartialDependenceDisplay

from_estimator

Partial dependence and individual conditional expectation curves

pd_results, axes_

inspection.DecisionBoundaryDisplay

from_estimator

Decision regions of a classifier on two features

xx0, xx1, response

ROC curves: from_estimator, from_predictions and combining curves

The official example plots a ROC curve with from_estimator, then draws a second model on the same Axes and re-draws the first display on it. The version below keeps that structure, uses a stratified split so both classes are present in the test half, and prints the stored values.

import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import RocCurveDisplay
from sklearn.model_selection import train_test_split

X, y = load_iris(return_X_y=True)
y = y == 2                                   # virginica against the rest
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, stratify=y, random_state=42)

clf = LogisticRegression(C=0.01, random_state=42).fit(X_train, y_train)
rfc = RandomForestClassifier(n_estimators=50, random_state=42).fit(X_train, y_train)

# 1. from_estimator: the display calls predict_proba/decision_function for you
clf_disp = RocCurveDisplay.from_estimator(clf, X_test, y_test, name="logistic regression")
print(type(clf_disp).__name__, round(clf_disp.roc_auc, 3), clf_disp.fpr.shape)

# 2. from_predictions: you supply the scores of the positive class
y_score = clf.predict_proba(X_test)[:, 1]
pred_disp = RocCurveDisplay.from_predictions(y_test, y_score, name="same model, from scores")
print(round(pred_disp.roc_auc, 3))

# 3. draw several curves on one Axes without recomputing anything
fig, ax = plt.subplots()
rfc_disp = RocCurveDisplay.from_estimator(rfc, X_test, y_test, ax=ax, name="forest", curve_kwargs={"alpha": 0.8})
clf_disp.plot(ax=ax, curve_kwargs={"alpha": 0.8})
print(round(rfc_disp.roc_auc, 3), rfc_disp.ax_ is ax, rfc_disp.figure_ is fig)
fig.savefig("roc.png", dpi=150)

Output:

RocCurveDisplay 0.978 (12,)
0.978
0.998 True True

Points worth noting:

  • name labels the curve in the legend. curve_kwargs carries Matplotlib line options such as alpha, color and linestyle.

  • clf_disp.plot(ax=ax) redraws the stored fpr, tpr and AUC: nothing is predicted again, which matters when the model is slow or the test set is large.

  • from_estimator returns instantly meaningful attributes (roc_auc), so you can also use a Display purely as a convenient container of ROC points and ignore the figure.

The positive class and from_predictions

from_predictions does not know which column of predict_proba you chose. The user guide spells out the rule: pass the column that belongs to pos_label, and for decision_function multiply the score by -1 when pos_label is not the last entry of classes_. Getting this wrong does not raise; it silently produces a mirrored curve with an AUC of 1 minus the true value. The example uses string labels where the positive class is the first class.

import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import RocCurveDisplay
from sklearn.model_selection import train_test_split

X, y01 = make_classification(500, random_state=0)
y = np.where(y01 == 1, "yes", "no")
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0, stratify=y)
clf = LogisticRegression().fit(X_train, y_train)
print(clf.classes_)

# the positive class is "no", the FIRST class
d_est = RocCurveDisplay.from_estimator(clf, X_test, y_test, pos_label="no")
good = RocCurveDisplay.from_predictions(y_test, clf.predict_proba(X_test)[:, 0], pos_label="no")
wrong = RocCurveDisplay.from_predictions(y_test, clf.predict_proba(X_test)[:, 1], pos_label="no")
dec = RocCurveDisplay.from_predictions(y_test, -clf.decision_function(X_test), pos_label="no")
for name, d in [("from_estimator", d_est), ("proba column 0", good), ("proba column 1", wrong), ("negated decision_function", dec)]:
    print(f"{name:28s} AUC = {d.roc_auc:.3f}")

Output:

['no' 'yes']
from_estimator               AUC = 0.898
proba column 0               AUC = 0.898
proba column 1               AUC = 0.102
negated decision_function    AUC = 0.898

from_estimator picks the right column and sign automatically from pos_label, which is the main reason to prefer it unless you must avoid recomputing predictions.

Confusion matrices

ConfusionMatrixDisplay has a normalize option ("true" divides each row by the number of true instances of the class, "pred" divides each column, "all" divides by the total), display_labels, values_format, cmap, xticks_rotation and colorbar. The matrix is stored in confusion_matrix, so you can print or test it as an array.

import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import ConfusionMatrixDisplay
from sklearn.model_selection import train_test_split

X, y = make_classification(n_samples=600, n_features=8, n_informative=4, n_classes=3, class_sep=0.7, random_state=0)
names = ["low", "medium", "high"]
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=0)
y_pred = LogisticRegression(max_iter=1000).fit(X_train, y_train).predict(X_test)

fig, axes = plt.subplots(1, 2, figsize=(10, 4))
counts = ConfusionMatrixDisplay.from_predictions(y_test, y_pred, display_labels=names, ax=axes[0], colorbar=False)
rates = ConfusionMatrixDisplay.from_predictions(y_test, y_pred, display_labels=names, normalize="true", values_format=".0%", cmap="Blues", ax=axes[1], colorbar=False)
axes[0].set_title("counts")
axes[1].set_title("row-normalised")
print(counts.confusion_matrix)
print(rates.confusion_matrix.round(2))
fig.tight_layout()
fig.savefig("confusion.png", dpi=150)

Output:

[[34  8  8]
 [14 29  8]
 [ 9 17 23]]
[[0.68 0.16 0.16]
 [0.27 0.57 0.16]
 [0.18 0.35 0.47]]

A row-normalised matrix reads as per-class recall (the diagonal), which is easier to compare across classes of different size than raw counts.

Precision-recall, DET and calibration plots

These three Displays answer different questions about a binary classifier and share the same constructors. On imbalanced problems the precision-recall curve is usually more informative than the ROC curve; the DET curve plots error rates directly and is common in biometrics; the reliability diagram checks whether predicted probabilities can be read as frequencies. See Probability Calibration for the theory.

import matplotlib.pyplot as plt
from sklearn.calibration import CalibrationDisplay
from sklearn.datasets import make_classification, make_regression
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.linear_model import Ridge
from sklearn.metrics import DetCurveDisplay, PrecisionRecallDisplay, PredictionErrorDisplay
from sklearn.model_selection import train_test_split

X, y = make_classification(n_samples=3000, flip_y=0.1, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0, stratify=y)
hgb = HistGradientBoostingClassifier(random_state=0).fit(X_train, y_train)

fig, axes = plt.subplots(1, 3, figsize=(14, 4))
pr = PrecisionRecallDisplay.from_estimator(hgb, X_test, y_test, ax=axes[0])
det = DetCurveDisplay.from_estimator(hgb, X_test, y_test, ax=axes[1])
cal = CalibrationDisplay.from_estimator(hgb, X_test, y_test, n_bins=10, strategy="quantile", ax=axes[2])
print("average precision:", round(pr.average_precision, 3))
print("calibration bins:", cal.prob_true.shape[0], cal.prob_pred.shape[0])
fig.tight_layout()
fig.savefig("classifier-displays.png", dpi=150)

Output:

average precision: 0.905
calibration bins: 10 10

CalibrationDisplay takes n_bins and strategy ("uniform" for equal-width bins, "quantile" for bins with equal numbers of samples); ref_line=True draws the diagonal of a perfectly calibrated model.

Regression: PredictionErrorDisplay

PredictionErrorDisplay draws one of two views of a regressor, chosen with kind: "actual_vs_predicted" (points should lie on the diagonal) or "residual_vs_predicted" (residuals should scatter around zero with no pattern). It subsamples to 1000 points by default (subsample).

import matplotlib.pyplot as plt
from sklearn.datasets import make_regression
from sklearn.linear_model import Ridge
from sklearn.metrics import PredictionErrorDisplay
from sklearn.model_selection import train_test_split

Xr, yr = make_regression(n_samples=400, n_features=6, noise=15, random_state=0)
Xr_train, Xr_test, yr_train, yr_test = train_test_split(Xr, yr, random_state=0)
ridge = Ridge().fit(Xr_train, yr_train)

fig, axes = plt.subplots(1, 2, figsize=(10, 4))
PredictionErrorDisplay.from_estimator(ridge, Xr_test, yr_test, kind="actual_vs_predicted", ax=axes[0])
PredictionErrorDisplay.from_estimator(ridge, Xr_test, yr_test, kind="residual_vs_predicted", ax=axes[1])
fig.savefig("regression-errors.png", dpi=150)

One curve per fold: from_cv_results

RocCurveDisplay.from_cv_results (since 1.7) and PrecisionRecallDisplay.from_cv_results (new in 1.9) draw the curve of every cross-validation fold from the dictionary returned by cross_validate. That dictionary must have been created with return_estimator=True and return_indices=True, because the display needs the fitted models and the test indices of each fold.

import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import PrecisionRecallDisplay, RocCurveDisplay
from sklearn.model_selection import StratifiedKFold, cross_validate

X, y = make_classification(n_samples=600, random_state=0)
cv_results = cross_validate(
    LogisticRegression(), X, y, cv=StratifiedKFold(5, shuffle=True, random_state=0),
    return_estimator=True, return_indices=True,       # both are needed by from_cv_results
)
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
roc = RocCurveDisplay.from_cv_results(cv_results, X, y, ax=axes[0], plot_chance_level=True)
pr = PrecisionRecallDisplay.from_cv_results(cv_results, X, y, ax=axes[1])
print(len(roc.roc_auc), [round(a, 3) for a in roc.roc_auc])
print(len(pr.average_precision))
fig.savefig("cv-curves.png", dpi=150)

Output:

5 [0.982, 0.993, 0.994, 0.976, 0.991]
5

With a Display created this way, roc_auc is a list with one value per fold, not a single number. The spread of those values is a more honest picture of variability than the mean alone. See Cross-Validation & Splitters.

Learning and validation curves

LearningCurveDisplay and ValidationCurveDisplay run the model selection helpers (learning_curve, validation_curve) and plot the result, so they accept the usual cv, scoring, n_jobs and train_sizes or param_range arguments. score_type is "test", "train" or "both", and std_display_style chooses between "fill_between", "errorbar" and None for the spread across folds.

import numpy as np
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import LearningCurveDisplay, StratifiedKFold, ValidationCurveDisplay
from sklearn.svm import SVC

X, y = load_iris(return_X_y=True)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
lc = LearningCurveDisplay.from_estimator(
    LogisticRegression(max_iter=1000), X, y,
    train_sizes=np.linspace(0.2, 1.0, 5), cv=cv, score_type="both", std_display_style="fill_between",
    shuffle=True, random_state=0,
)
print(lc.train_sizes)
print(lc.test_scores.mean(axis=1).round(3))
vc = ValidationCurveDisplay.from_estimator(SVC(), X, y, param_name="gamma", param_range=np.logspace(-4, 1, 6), cv=cv, score_type="both")
print(vc.param_range)
print(vc.test_scores.mean(axis=1).round(3))
lc.figure_.savefig("lc.png")

Output:

[ 24  48  72  96 120]
[0.927 0.947 0.96  0.973 0.96 ]
[1.e-04 1.e-03 1.e-02 1.e-01 1.e+00 1.e+01]
[0.92  0.92  0.953 0.947 0.967 0.94 ]

The shuffle=True, random_state=0 arguments of LearningCurveDisplay.from_estimator are not decoration. The learning curve trains on the first n rows of each training fold, and the iris data set is sorted by class. Without shuffling, the smallest training size contains a single class and LogisticRegression raises "needs samples of at least 2 classes"; learning_curve catches that, reports FitFailedWarning, records nan for that size and the plot has a hole. A sorted file, or any data ordered by time or by group, needs the same care. See Validation & Learning Curves for how to read the curves.

Partial dependence

PartialDependenceDisplay.from_estimator accepts feature indices or names and tuples for two-way interactions. kind chooses "average", "individual" (ICE curves) or "both"; subsample and random_state limit the ICE curves and the background data; n_jobs parallelises the computation. A pandas DataFrame lets you refer to columns by name.

import matplotlib.pyplot as plt
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.inspection import PartialDependenceDisplay
from sklearn.model_selection import train_test_split

X, y = fetch_california_housing(as_frame=True, return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
model = HistGradientBoostingRegressor(random_state=0).fit(X_train, y_train)
disp = PartialDependenceDisplay.from_estimator(
    model, X_test, ["MedInc", "AveOccup", ("MedInc", "AveOccup")], subsample=500, random_state=0, n_jobs=1,
)
print(disp.axes_.shape, [a.get_xlabel() for a in disp.axes_.ravel()])
disp.figure_.savefig("pdp.png", dpi=150)

Output:

(1, 3) ['MedInc', 'AveOccup', 'MedInc']

The data are downloaded the first time fetch_california_housing runs; see Dataset Loaders & Generators. The interpretation of the curves, and their pitfalls with correlated features, is in Permutation Importance & Partial Dependence.

Decision boundaries

DecisionBoundaryDisplay evaluates a classifier on a regular grid of two features and draws the regions. It has no from_predictions, because it needs the estimator to predict on the grid. response_method selects "predict", "predict_proba" or "decision_function"; plot_method selects the Matplotlib routine ("contourf", "contour", "pcolormesh"); grid_resolution controls the grid; class_of_interest picks which class to show for probability responses on multiclass models. For models trained on more than two features, fit them on the two columns you plan to draw, or the grid has no meaning.

import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
from sklearn.inspection import DecisionBoundaryDisplay
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC

X, y = make_moons(n_samples=200, noise=0.25, random_state=0)
fig, axes = plt.subplots(1, 2, figsize=(10, 4), sharey=True)
for ax, model in zip(axes, [KNeighborsClassifier(15), SVC(gamma=2)]):
    model.fit(X, y)
    disp = DecisionBoundaryDisplay.from_estimator(
        model, X, response_method="predict", plot_method="pcolormesh", alpha=0.4, grid_resolution=200, ax=ax,
    )
    disp.ax_.scatter(X[:, 0], X[:, 1], c=y, edgecolor="k")
    ax.set_title(type(model).__name__)
print(disp.xx0.shape, disp.response.shape)
fig.savefig("boundary.png", dpi=150)

Output:

(200, 200) (200, 200)

The 1.7 to 1.9 releases fixed several multiclass issues in this class (consistent colours through multiclass_colors, all class boundaries with plot_method="contour", and a ValueError when the colormap has fewer colours than classes), so an older release can draw multiclass boundaries differently from 1.9.

Customising and reusing displays

  • Axes and layout. Pass ax= to draw into a subplot, or let the Display create its own figure and use ax_ and figure_ afterwards. Displays that draw several panels (partial dependence) store an array in axes_.

  • Style options. The Matplotlib options go in dictionaries named after what they style, such as curve_kwargs, scatter_kwargs, line_kwargs and im_kw/text_kw for the confusion matrix; the exact names are in each class’s API reference.

  • Reuse. display.plot(ax=...) repeats the drawing without recomputation. This is the pattern for overlaying curves of several models, or for a slide and a paper version of the same figure.

  • Use the numbers. The stored attributes are plain NumPy arrays: display.fpr, display.tpr, display.confusion_matrix. Saving them is often better than saving a picture.

  • Do not initialise directly. The class constructors expect already-computed values and are meant for the class methods; the user guide recommends from_estimator or from_predictions.

Removed functions and older tutorials

Tutorials written before scikit-learn 1.2 call module-level functions that no longer exist. Replace them as follows.

Removed function Use instead Removed in

plot_confusion_matrix(clf, X, y)

ConfusionMatrixDisplay.from_estimator(clf, X, y)

1.2

plot_roc_curve(clf, X, y)

RocCurveDisplay.from_estimator(clf, X, y)

1.2

plot_precision_recall_curve(clf, X, y)

PrecisionRecallDisplay.from_estimator(clf, X, y)

1.2

plot_det_curve(clf, X, y)

DetCurveDisplay.from_estimator(clf, X, y)

1.2

plot_partial_dependence(clf, X, features)

PartialDependenceDisplay.from_estimator(clf, X, features)

1.2

sklearn.learning_curve and sklearn.grid_search modules (0.18)

sklearn.model_selection

moved in 0.18

Calling any of the plot_* names on scikit-learn 1.9.1 raises an ImportError or AttributeError, which was confirmed for sklearn.inspection.plot_partial_dependence and for the plot_* names in sklearn.metrics. Two renames in the Display methods also affect copied code. RocCurveDisplay.from_predictions renamed y_pred to y_score in 1.7, and the old name was removed in 1.9 (passing y_pred= raises a TypeError). DetCurveDisplay.from_predictions and PrecisionRecallDisplay.from_predictions deprecated y_pred in favour of y_score in 1.8, with removal planned for 1.10. Passing the scores positionally avoids the problem.

Common pitfalls

  • Plotting on training data. from_estimator(model, X_train, y_train) gives optimistic curves. Draw the test set, or use from_cv_results.

  • Wrong positive class with from_predictions. See the AUC of 0.102 above.

  • Unshuffled data in learning curves. See the learning-curve section.

  • A figure is not a metric. A smooth ROC curve says little about a rare class; pair it with the precision-recall curve and the numbers in Metrics & Scoring.

  • Notebook state. In a notebook, plt.gca() returns whichever Axes was current; pass ax= explicitly when drawing several displays.

  • Headless servers. Use matplotlib.use("Agg") or set MPLBACKEND=Agg, then savefig.