# How to Plot a ROC Curve and Calculate AUC in Python

> Plot a ROC curve and calculate AUC in Python using scikit-learn's RocCurveDisplay, roc_curve, and roc_auc_score. Covers model comparison, choosing a threshold, multiclass one-vs-rest curves, and cross-validated ROC.

Source: https://www.pythoncharts.com/machine-learning/roc-curve-auc-python/ | Published: 2026-11-25 | Author: Alex Scott | Category: Machine Learning | Tags: machine learning, scikit-learn, roc curve, auc, classification, model evaluation, matplotlib

To plot a ROC curve in Python, use `RocCurveDisplay.from_estimator(model, X_test, y_test)` from scikit-learn. It draws the true positive rate against the false positive rate across every possible threshold, and shows the area under the curve (AUC) in the legend. For just the number, `roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])` returns the AUC. The code below targets scikit-learn 1.9.

## Quick Example

This compares two models on one plot. The data is synthetic (about 20% positives), so it runs without any downloads.

```python
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
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 = make_classification(n_samples=2000, n_features=12, n_informative=5,
                           weights=[0.8, 0.2], flip_y=0.05, class_sep=0.8,
                           random_state=7)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, stratify=y, random_state=7)

logreg = LogisticRegression(max_iter=1000).fit(X_train, y_train)
forest = RandomForestClassifier(n_estimators=200, random_state=7).fit(X_train, y_train)

fig, ax = plt.subplots(figsize=(6, 6))
RocCurveDisplay.from_estimator(logreg, X_test, y_test, name="Logistic regression",
                               curve_kwargs={"color": "#0f766e", "lw": 2}, ax=ax)
RocCurveDisplay.from_estimator(forest, X_test, y_test, name="Random forest",
                               curve_kwargs={"color": "#c2410c", "lw": 2}, ax=ax,
                               plot_chance_level=True, chance_level_kw={"color": "#94a3b8"})
ax.set(xlabel="False positive rate", ylabel="True positive rate",
       title="ROC curve: churn model comparison")
```

![ROC curves for a logistic regression and a random forest, with the random forest curve bowing closer to the top-left corner and a dashed diagonal chance line](https://www.pythoncharts.com/machine-learning/roc-curve-auc-python/images/roc-curve-quick-example.png)

The random forest (AUC 0.88) sits above logistic regression (AUC 0.80) across almost the whole plot, so at any false positive rate it catches more of the true positives. The dashed diagonal is a model guessing at random, with an AUC of 0.5. Pass each call the same `ax` to overlay curves, and `plot_chance_level=True` once to draw the diagonal.

In scikit-learn 1.9 the line styling goes through `curve_kwargs`. Older versions took `color=` and `lw=` directly, which now raises a `TypeError`.

## What a ROC Curve Shows

A classifier outputs a score (usually a probability) for each row, and you pick a threshold to turn that into a yes or no. A ROC curve sweeps that threshold from high to low and records two rates at each step:

- **True positive rate (TPR, recall):** the share of actual positives you catch.
- **False positive rate (FPR):** the share of actual negatives you wrongly flag.

A strict threshold sits near the bottom-left (few flags, few mistakes). A loose threshold sits near the top-right (you catch everything and flag everything). A better model bends toward the top-left corner, which is high TPR at low FPR.

AUC summarizes the curve as one number. It equals the probability that a randomly chosen positive gets a higher score than a randomly chosen negative. 1.0 is perfect ranking, 0.5 is random.

## Calculate AUC with roc_auc_score

```python
from sklearn.metrics import roc_auc_score

roc_auc_score(y_test, logreg.predict_proba(X_test)[:, 1])   # 0.80
roc_auc_score(y_test, forest.predict_proba(X_test)[:, 1])   # 0.88
```

Pass the scores for the positive class, not the hard 0/1 predictions. `predict_proba(X)[:, 1]` works for most models, and `decision_function(X)` works too for models like `LinearSVC`. Feeding `predict()` output collapses the curve to a single point and gives a misleading AUC.

## Plot a ROC Curve Manually with roc_curve

`roc_curve` returns the raw arrays, which you need when you want to label thresholds or style the plot yourself.

```python
import numpy as np
from sklearn.metrics import auc, roc_curve

scores = forest.predict_proba(X_test)[:, 1]
fpr, tpr, thresholds = roc_curve(y_test, scores)
best = np.argmax(tpr - fpr)  # Youden's J statistic

fig, ax = plt.subplots(figsize=(6, 6))
ax.plot(fpr, tpr, color="#c2410c", lw=2, label=f"Random forest (AUC = {auc(fpr, tpr):.2f})")
ax.plot([0, 1], [0, 1], "--", color="#94a3b8", label="Chance")
for t in (0.2, 0.5, 0.8):
    i = np.argmin(np.abs(thresholds - t))
    ax.scatter(fpr[i], tpr[i], s=40, color="#1e293b", zorder=3)
    ax.annotate(f"threshold {t}", (fpr[i], tpr[i]), textcoords="offset points",
                xytext=(10, -14), fontsize=9)
ax.scatter(fpr[best], tpr[best], s=140, facecolor="none", edgecolor="#0f766e",
           lw=2, zorder=4, label=f"Best cutoff ({thresholds[best]:.2f})")
ax.set(xlabel="False positive rate", ylabel="True positive rate",
       title="Where each threshold lands on the curve")
ax.legend(loc="lower right")
ax.set_aspect("equal")
```

![ROC curve for a random forest with three labeled threshold points and a circle marking the best cutoff near the top-left of the curve](https://www.pythoncharts.com/machine-learning/roc-curve-auc-python/images/roc-curve-thresholds.png)

`thresholds` lines up with `fpr` and `tpr`, so each point on the curve is a specific cutoff. On this model:

| Threshold | FPR | TPR |
|---|---|---|
| 0.2 | 0.20 | 0.83 |
| 0.33 (best by Youden's J) | 0.07 | 0.76 |
| 0.5 | 0.03 | 0.64 |
| 0.8 | 0.00 | 0.20 |

The default 0.5 cutoff catches 64% of positives. Dropping to 0.33 catches 76% while flagging 7% of negatives instead of 3%. Whether that trade is worth it depends on what a false alarm costs compared with a miss, which the ROC curve can't tell you.

## How Do I Choose a Threshold from the ROC Curve?

`np.argmax(tpr - fpr)` picks the point farthest above the diagonal, known as Youden's J statistic. It treats misses and false alarms as equally costly. If they aren't, weight the two rates (for example `tpr - 0.3 * fpr`), or pick the lowest threshold that keeps FPR under a limit you can accept. Then apply it yourself:

```python
y_pred = (scores >= thresholds[best]).astype(int)
```

`predict()` always uses 0.5 for probabilistic models, so a custom cutoff means thresholding the scores directly. A [confusion matrix](https://www.pythoncharts.com/python/confusion-matrix-seaborn-scikit-learn/) at the chosen threshold shows what that trade looks like in counts.

## Multiclass ROC Curves (One-vs-Rest)

ROC is defined for two classes. For three or more, treat each class as "this class vs everything else" and draw one curve per class.

```python
from sklearn.preprocessing import label_binarize

X3, y3 = make_classification(n_samples=2400, n_features=10, n_informative=6,
                             n_classes=3, n_clusters_per_class=1, class_sep=0.9,
                             random_state=3)
X3_train, X3_test, y3_train, y3_test = train_test_split(
    X3, y3, test_size=0.3, stratify=y3, random_state=3)
clf = LogisticRegression(max_iter=1000).fit(X3_train, y3_train)
proba = clf.predict_proba(X3_test)
y3_bin = label_binarize(y3_test, classes=[0, 1, 2])

fig, ax = plt.subplots(figsize=(6, 6))
colors = ["#7c3aed", "#d97706", "#0891b2"]
for k, color in enumerate(colors):
    RocCurveDisplay.from_predictions(y3_bin[:, k], proba[:, k], name=f"Class {k} vs rest",
                                     curve_kwargs={"color": color, "lw": 2}, ax=ax)
ax.plot([0, 1], [0, 1], "--", color="#94a3b8")
ax.set(xlabel="False positive rate", ylabel="True positive rate",
       title="Multiclass ROC (one-vs-rest)")
```

![Three one-vs-rest ROC curves for a three-class classifier, with class 0 highest at AUC 0.96, class 2 at 0.94, and class 1 lowest at 0.87](https://www.pythoncharts.com/machine-learning/roc-curve-auc-python/images/roc-curve-multiclass.png)

Class 0 is the easiest to separate (AUC 0.96) and class 1 the hardest (0.87). For one summary number, `roc_auc_score(y3_test, proba, multi_class="ovr", average="macro")` averages the three AUCs, which comes to 0.92 here. Note that the `proba` array must have one column per class and its rows must sum to 1, which `predict_proba` guarantees.

## Cross-Validated ROC with a Confidence Band

One train/test split gives one curve, and with a small test set that curve is noisy. Running the curve across folds shows how much the result moves. Interpolate each fold's TPR onto a shared FPR grid so the curves can be averaged:

```python
from sklearn.model_selection import StratifiedKFold

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=7)
mean_fpr = np.linspace(0, 1, 101)
tprs, aucs = [], []

fig, ax = plt.subplots(figsize=(6, 6))
for tr, te in cv.split(X, y):
    model = LogisticRegression(max_iter=1000).fit(X[tr], y[tr])
    f, t, _ = roc_curve(y[te], model.predict_proba(X[te])[:, 1])
    tprs.append(np.interp(mean_fpr, f, t))
    aucs.append(auc(f, t))
    ax.plot(f, t, color="#0f766e", alpha=0.25, lw=1)

mean_tpr = np.mean(tprs, axis=0)
std_tpr = np.std(tprs, axis=0)
ax.plot(mean_fpr, mean_tpr, color="#0f766e", lw=2.5,
        label=f"Mean ROC (AUC = {np.mean(aucs):.2f} ± {np.std(aucs):.2f})")
ax.fill_between(mean_fpr, mean_tpr - std_tpr, mean_tpr + std_tpr,
                color="#0f766e", alpha=0.15, label="± 1 std. dev.")
ax.plot([0, 1], [0, 1], "--", color="#94a3b8", label="Chance")
ax.set(xlabel="False positive rate", ylabel="True positive rate",
       title="5-fold cross-validated ROC")
ax.legend(loc="lower right")
ax.set_aspect("equal")
```

![Five faint ROC curves from cross-validation folds with a bold mean curve and a shaded one standard deviation band around it](https://www.pythoncharts.com/machine-learning/roc-curve-auc-python/images/roc-curve-cross-validated.png)

The mean AUC for logistic regression is 0.81 ± 0.03, and individual folds range from 0.77 to 0.87. That spread is a good reason not to read much into a 0.01 AUC difference between two models on a single split.

## When Is ROC AUC Misleading?

ROC curves are the standard choice, but they have a known weak spot. On heavily imbalanced data, FPR is divided by a large number of negatives, so a model can post a high AUC while most of its flagged rows are false alarms. When positives are rare and you care about the precision of what you flag, use a precision-recall curve alongside it.

| Situation | Better choice |
|---|---|
| Balanced classes, ranking quality matters | ROC curve and AUC |
| Rare positives, flagged rows are expensive to review | Precision-recall curve |
| You need a single decision, not a ranking | Confusion matrix at a chosen threshold |
| Comparing models on small data | Cross-validated ROC |

## Similar Topics

- [How to Plot a Confusion Matrix using Seaborn or Scikit-Learn](https://www.pythoncharts.com/python/confusion-matrix-seaborn-scikit-learn/)
- [Matplotlib Legend Outside the Plot](https://www.pythoncharts.com/matplotlib/matplotlib-legend-outside/)
- [Confidence Interval Bands in Seaborn](https://www.pythoncharts.com/seaborn/seaborn-confidence-interval-bands/)
- [Machine Learning Charts in Python: A Guide to Evaluating and Exploring Models](https://www.pythoncharts.com/machine-learning/machine-learning-python-guide/)
