# How to Plot a Precision-Recall Curve in Python

> Plot a precision-recall curve in Python using scikit-learn's PrecisionRecallDisplay and precision_recall_curve. Covers average precision, why PR curves beat ROC on imbalanced data, F1-optimal thresholds, and choosing an operating point.

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

To plot a precision-recall curve in Python, use `PrecisionRecallDisplay.from_estimator(model, X_test, y_test)` from scikit-learn. It plots precision against recall for every possible threshold and puts the average precision (AP) in the legend. For the number alone, `average_precision_score(y_test, model.predict_proba(X_test)[:, 1])` returns it. The code below targets scikit-learn 1.9.

## Quick Example

This compares two models on a synthetic fraud-style dataset where only about 2% of rows are positive. It runs without downloads.

```python
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import PrecisionRecallDisplay, average_precision_score
from sklearn.model_selection import train_test_split

X, y = make_classification(n_samples=40000, n_features=15, n_informative=6,
                           weights=[0.98, 0.02], flip_y=0.002, class_sep=0.9,
                           random_state=21)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.4, stratify=y, random_state=21)

logreg = LogisticRegression(max_iter=1000).fit(X_train, y_train)
boost = HistGradientBoostingClassifier(random_state=21).fit(X_train, y_train)

fig, ax = plt.subplots(figsize=(6, 5.5))
PrecisionRecallDisplay.from_estimator(logreg, X_test, y_test, name="Logistic regression",
                                      curve_kwargs={"color": "#7c3aed", "lw": 2}, ax=ax)
PrecisionRecallDisplay.from_estimator(boost, X_test, y_test, name="Gradient boosting",
                                      curve_kwargs={"color": "#e11d48", "lw": 2}, ax=ax,
                                      plot_chance_level=True,
                                      chance_level_kw={"color": "#94a3b8"})
ax.set(xlabel="Recall", ylabel="Precision",
       title="Precision-recall curve: fraud model comparison")
ax.legend(loc="lower left")

for name, model in [("logreg", logreg), ("boost", boost)]:
    print(name, round(average_precision_score(y_test, model.predict_proba(X_test)[:, 1]), 3))
```

![Precision-recall curves for logistic regression and gradient boosting on 2% positive data, with the gradient boosting curve far above and a dashed chance line near 0.02](https://www.pythoncharts.com/machine-learning/precision-recall-curve-python/images/pr-curve-quick-example.png)

Gradient boosting (AP 0.70) holds higher precision than logistic regression (AP 0.38) at every recall level. The dashed line is the chance level. For a PR curve it is a flat line at the share of positives in the test set (0.02 here), not a diagonal. A model that guesses at random gets precision equal to the base rate no matter how many cases it flags.

In scikit-learn 1.9 line styling goes through `curve_kwargs`, the same as `RocCurveDisplay`. Older versions took `color=` and `lw=` directly.

## What a Precision-Recall Curve Shows

A classifier gives each row a score, and a threshold turns scores into yes/no predictions. The PR curve sweeps that threshold from high to low and records two numbers:

- **Precision:** of the rows you flagged, the share that are really positive (`TP / (TP + FP)`).
- **Recall:** of all the real positives, the share you flagged (`TP / (TP + FN)`). It is the same quantity as the true positive rate on a ROC curve.

A strict threshold flags few rows, so precision is high and recall is low (top-left). A loose threshold flags almost everything, so recall climbs to 1 while precision falls to the base rate (bottom-right). A better model keeps precision high for longer as recall grows, pushing the curve toward the top-right corner.

## Average Precision vs the Area Under the PR Curve

`average_precision_score(y_true, y_score)` summarizes the curve as a weighted mean of the precision at each threshold, weighted by the increase in recall:

```python
ap = average_precision_score(y_test, boost.predict_proba(X_test)[:, 1])
print(f"AP = {ap:.3f}")
```

Use it in place of `auc(recall, precision)`. Linearly interpolating between PR points (what the trapezoid rule in `auc` does) is too optimistic, because the curve is not linear between thresholds. AP uses a step-wise sum and avoids that.

AP is also the number you want for `cross_val_score` or a grid search on imbalanced data: pass `scoring="average_precision"`.

## Should I Use a PR Curve or a ROC Curve?

Use a PR curve when positives are rare and you care about them, such as fraud, churn, or defect detection. ROC curves count false positives as a share of all negatives. When there are 15,000 negatives, 300 false alarms move the false positive rate only to 2%, so the curve looks excellent while the model is still wrong about most of its flags.

The same gradient boosting model on the same test set shows both views:

![Side by side ROC curve with AUC 0.95 and precision-recall curve with AP 0.70 for the same model, the ROC curve hugging the top-left corner while the precision-recall curve falls steadily](https://www.pythoncharts.com/machine-learning/precision-recall-curve-python/images/pr-vs-roc.png)

The ROC curve reads 0.95 AUC and hugs the top-left corner. The PR curve for the same predictions has AP 0.70, and precision drops below 0.5 once recall passes about 0.72. The test set has 334 positives out of 16,000 rows (2.1%), so the PR curve is the one that shows what an analyst reviewing flagged cases would experience.

| | ROC curve | Precision-recall curve |
|---|---|---|
| Axes | False positive rate vs recall | Recall vs precision |
| Chance level | Diagonal, AUC 0.5 | Flat line at the positive rate |
| Affected by class balance | Barely | Strongly |
| Best for | Balanced classes, ranking quality overall | Rare positives, flagged-case quality |
| Summary number | `roc_auc_score` | `average_precision_score` |

For the other view, see [how to plot a ROC curve and calculate AUC](https://www.pythoncharts.com/machine-learning/roc-curve-auc-python/).

## Plot a Precision-Recall Curve Manually with precision_recall_curve

`PrecisionRecallDisplay` is a thin wrapper. To get the raw numbers, call `precision_recall_curve` on the scores. It returns one more precision and recall value than thresholds, because the final point (precision 1, recall 0) has no threshold:

```python
import numpy as np
from sklearn.metrics import precision_recall_curve

scores = boost.predict_proba(X_test)[:, 1]
precision, recall, thresholds = precision_recall_curve(y_test, scores)
print(len(precision), len(thresholds))
```

Drop the last element of `precision` and `recall` when you line them up against `thresholds`.

## How Do I Pick a Threshold from the Precision-Recall Curve?

Two common approaches. The first maximizes F1, the harmonic mean of precision and recall:

```python
p, r = precision[:-1], recall[:-1]
f1 = 2 * p * r / np.clip(p + r, 1e-12, None)
best = np.argmax(f1)
print(f"threshold {thresholds[best]:.2f}: "
      f"precision {p[best]:.2f}, recall {r[best]:.2f}, F1 {f1[best]:.2f}")

fig, ax = plt.subplots(figsize=(7, 4.5))
ax.plot(thresholds, p, color="#7c3aed", lw=2, label="Precision")
ax.plot(thresholds, r, color="#0ea5e9", lw=2, label="Recall")
ax.plot(thresholds, f1, color="#e11d48", lw=2, ls="--", label="F1")
ax.axvline(thresholds[best], color="#64748b", lw=1, ls=":")
ax.set(xlabel="Decision threshold", ylabel="Score", ylim=(0, 1.02),
       title="Precision, recall, and F1 as the threshold moves")
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.15), ncol=3, frameon=False)
```

![Line chart of precision, recall, and F1 against the decision threshold, with a dotted vertical line at the F1 peak of 0.67 near threshold 0.24](https://www.pythoncharts.com/machine-learning/precision-recall-curve-python/images/pr-threshold.png)

F1 peaks at 0.67 around a threshold of 0.24 (precision 0.76, recall 0.59). That default weights precision and recall equally, which rarely matches real costs. The second approach is to start from a business constraint, such as "we can review enough cases to catch 60% of fraud", and take the highest threshold that still meets it:

```python
idx = np.where(r >= 0.60)[0][-1]
print(f"threshold {thresholds[idx]:.2f}: precision {p[idx]:.2f}, recall {r[idx]:.2f}")

fig, ax = plt.subplots(figsize=(6, 5))
ax.plot(recall, precision, color="#e11d48", lw=2)
ax.scatter(r[idx], p[idx], s=70, color="#0f172a", zorder=3)
ax.axhline(y_test.mean(), color="#94a3b8", ls="--", lw=1)
ax.set(xlabel="Recall", ylabel="Precision", xlim=(0, 1.02), ylim=(0, 1.02),
       title="Operating point that keeps 60% recall")
```

![Precision-recall curve with a marked point at threshold 0.20 where precision is 0.72 and recall is 0.60](https://www.pythoncharts.com/machine-learning/precision-recall-curve-python/images/pr-operating-point.png)

Because recall falls as the threshold rises, `r >= 0.60` is true for a prefix of the array and `[-1]` picks the last (highest-threshold) entry. A threshold of 0.20 gives precision 0.72 and recall 0.60: roughly 7 in 10 flagged rows are real fraud while catching 60% of it.

Pick the threshold on validation data and report it on a separate test set. A threshold tuned on the same rows you evaluate on gives optimistic numbers.

## Practical Tips

- **Always show the base rate.** `plot_chance_level=True` draws it. An AP of 0.30 is strong when 1% of rows are positive and weak when 40% are.
- **Compare models on the same test set.** AP depends on the positive rate, so two models scored on different splits are not comparable.
- **Expect jagged curves with few positives.** The curve above has 334 positives. With 30, one flagged case moves precision visibly, so use cross-validation or bootstrap the AP before declaring a winner.
- **Multiclass:** binarize the labels with `label_binarize` and draw one PR curve per class (one-vs-rest), as in the ROC post.
- **Calibrated scores aren't required.** PR and ROC curves depend only on how the scores rank rows, so you can use `decision_function` output instead of probabilities.

## Similar Topics

- [How to Plot a ROC Curve and Calculate AUC in Python](https://www.pythoncharts.com/machine-learning/roc-curve-auc-python/)
- [How to Plot a Confusion Matrix using Seaborn or Scikit-Learn](https://www.pythoncharts.com/python/confusion-matrix-seaborn-scikit-learn/)
- [SHAP Plots in Python](https://www.pythoncharts.com/machine-learning/shap-plots-python/)
- [Machine Learning Charts in Python: A Guide to Evaluating and Exploring Models](https://www.pythoncharts.com/machine-learning/machine-learning-python-guide/)
