Residual Plot for Regression in Python with scikit-learn

Draw residual plots for a regression model with scikit-learn's PredictionErrorDisplay, learn to read curves, fans and outliers, and fix them with a log-transformed target.

A residual plot puts a regression model's predictions on the x-axis and its errors (actual minus predicted) on the y-axis. In scikit-learn, use PredictionErrorDisplay.from_predictions(y_true, y_pred, kind="residual_vs_predicted"). A healthy model gives a shapeless cloud around zero. A curve, a fan or a few far-off points tell you what to fix. The code targets scikit-learn 1.9.

Quick Example

This fits a linear regression on simulated apartment rents and draws the two plots PredictionErrorDisplay offers: actual vs predicted, and residuals vs predicted.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import PredictionErrorDisplay, r2_score
from sklearn.model_selection import train_test_split

# Sample data: each extra sq ft and year multiplies rent by a fixed percentage
rng = np.random.default_rng(23)
n = 1500
sqft = rng.uniform(350, 2200, n)
age = rng.uniform(0, 60, n)
beds = np.clip(np.round(sqft / 600 + rng.normal(0, 0.5, n)), 0, 5)
rent = np.exp(6.0 + 0.0009 * sqft - 0.004 * age + rng.normal(0, 0.12, n))
X = pd.DataFrame({"sqft": sqft, "age": age, "bedrooms": beds})
X_train, X_test, y_train, y_test = train_test_split(X, rent, test_size=0.3, random_state=0)

lin = LinearRegression().fit(X_train, y_train)
pred = lin.predict(X_test)
print("test R2:", round(r2_score(y_test, pred), 3))

fig, axes = plt.subplots(1, 2, figsize=(10, 4.2))
PredictionErrorDisplay.from_predictions(y_test, pred, kind="actual_vs_predicted",
                                        scatter_kwargs={"alpha": 0.4, "s": 12, "color": "#1b6ca8"}, ax=axes[0])
PredictionErrorDisplay.from_predictions(y_test, pred, kind="residual_vs_predicted",
                                        scatter_kwargs={"alpha": 0.4, "s": 12, "color": "#1b6ca8"}, ax=axes[1])
axes[0].set_title("Actual vs predicted")
axes[1].set_title("Residuals vs predicted")
fig.tight_layout()

Two scatter plots for a linear regression on rent. Left: actual vs predicted values hugging the diagonal but bending away from it at both ends. Right: residuals vs predicted forming a U shape, with the spread widening on the right

The test R² is 0.879, which looks fine. The residual plot says otherwise. Residuals are positive for the cheapest units, negative in the middle, and positive again for the most expensive ones, so the model is systematically wrong in a curved way. The spread also widens as predictions grow. The R² number alone would not have shown either problem.

What Does a Residual Plot Show?

A residual is y_true - y_pred. If the model captured the real relationship, what is left over is noise, and noise should have no pattern. Plotting residuals against the predicted value (rather than against one feature) gives a single view that works for any number of features. For a linear model with one predictor, the shapes look the same either way.

PredictionErrorDisplay has two modes:

kind= x-axis y-axis Use it to
"residual_vs_predicted" Predicted value Actual minus predicted Spot curves, fans, outliers
"actual_vs_predicted" Predicted value Actual value See how far points sit from the perfect-prediction diagonal

By default it subsamples to 1,000 points (subsample=1000) and fixes the sample with random_state. Pass subsample=None to plot every point, or a float for a fraction.

How to Read Residual Plot Patterns

Four shapes cover most of what you will see. These are drawn from small simulated datasets with a simple linear model fitted to each.

Four residual plots: a healthy random cloud around zero, a U-shaped curve, a fan that widens to the right, and a flat cloud with a handful of far-off outliers

Pattern What it means Usual fix
Shapeless cloud around 0, constant width Nothing obvious left to learn None needed
Curve (U shape or arch) The model is missing a non-linear relationship Add a squared or interaction term, transform a feature, or use a tree-based model
Fan (spread grows with the prediction) Heteroscedasticity: error scales with the size of the target Model log(y), or use a loss that suits the noise
A few points far from the rest Outliers or data errors Inspect those rows, then consider a robust loss such as HuberRegressor

Heteroscedasticity does not bias the coefficients of a linear model, but it makes standard errors and prediction intervals unreliable, and the large-target rows dominate the fit.

How to Fix a Curved or Fanning Residual Plot with a Log Target

When the target grows by percentages (prices, rents, incomes, counts), the errors are multiplicative: a 10% miss on a $2,000 rent is a bigger dollar error than on a $500 one. That gives both the curve and the fan. Fitting the model on log(y) and converting predictions back with exp handles this. TransformedTargetRegressor does the round trip for you:

from sklearn.compose import TransformedTargetRegressor

logm = TransformedTargetRegressor(regressor=LinearRegression(), func=np.log, inverse_func=np.exp)
logm.fit(X_train, y_train)
pred_log = logm.predict(X_test)
print("test R2 (dollars):", round(r2_score(y_test, pred_log), 3))

rel_lin = (y_test - pred) / pred
rel_log = (y_test - pred_log) / pred_log

fig, axes = plt.subplots(1, 2, figsize=(10, 4.2), sharey=True)
for ax, p, e, t, c in [(axes[0], pred, rel_lin, "Linear model on rent", "#e76f51"),
                       (axes[1], pred_log, rel_log, "Linear model on log(rent)", "#2a9d8f")]:
    ax.scatter(p, e * 100, s=12, alpha=0.4, color=c)
    ax.axhline(0, color="black", lw=1, ls="--")
    ax.set_title(t)
    ax.set_xlabel("Predicted rent ($)")
axes[0].set_ylabel("Residual (% of predicted rent)")
fig.tight_layout()

Residuals as a percentage of predicted rent. The plain linear model on the left curves sharply upward for cheap units, reaching over 100 percent. The log-target model on the right is a flat cloud around zero

Residuals here are shown as a percentage of the predicted rent, so the two models are on a comparable scale. The plain linear model overshoots badly for cheap units (the worst misses are over 100% of the prediction) and its percentage errors have a standard deviation of 0.228. After the log transform the cloud is flat and the standard deviation drops to 0.122. Test R² in dollars rises from 0.879 to 0.911.

When you do not know the right transform, a tree-based model such as HistGradientBoostingRegressor can absorb the curve on its own. A residual plot of its predictions is still worth drawing, because a fan can remain.

Check Normality of Residuals with a Q-Q Plot

Some uses of a regression (confidence intervals, p-values from statsmodels) assume roughly normal residuals. A Q-Q plot compares residual quantiles to a normal distribution. Points on the line mean normal, and curving away at the ends means heavier tails or skew.

from scipy import stats

fig, axes = plt.subplots(1, 2, figsize=(10, 4.2))
for ax, e, t, c in [(axes[0], rel_lin * 100, "Linear model", "#e76f51"),
                    (axes[1], rel_log * 100, "Log-target model", "#2a9d8f")]:
    stats.probplot(np.asarray(e), dist="norm", plot=ax)
    ax.get_lines()[0].set_color(c)
    ax.get_lines()[0].set_markersize(3)
    ax.get_lines()[1].set_color("black")
    ax.set_title(f"Q-Q plot of residuals: {t}")
    ax.set_ylabel("Residual (% of predicted rent)")
fig.tight_layout()
print("skew:", round(float(stats.skew(rel_lin)), 2), round(float(stats.skew(rel_log)), 2))

Two Q-Q plots of regression residuals. The linear model on the left bends far above the reference line on the right tail. The log-target model on the right follows the line closely

The linear model's residuals are strongly right-skewed (skewness 2.35) and bend away from the line. The log-target model's residuals sit close to it (skewness 0.29), with only slight tails. statsmodels has sm.qqplot(resid, line="s") if you prefer it.

Residual Plot or Actual vs Predicted?

Use both, for different questions.

Plot Answers Weakness
Residuals vs predicted Is the error random? Where is it biased? Says nothing about overall fit in the original units
Actual vs predicted How close are predictions overall? Curves and fans are easy to miss against a diagonal

The residual plot is the one that finds problems. Actual vs predicted is the one you show stakeholders.

Practical Tips

  • Plot residuals on the test set or out of fold (cross_val_predict). Training residuals flatter flexible models.
  • Draw residuals against individual features as well. A pattern against age that is invisible against the prediction points to one specific feature needing a transform.
  • With very large datasets, lower alpha or subsample to avoid a solid blob.
  • Do not chase every outlier. Look at the rows first: a data error should be fixed, a genuine extreme value should be kept.
  • A low R² with a clean residual plot means the data is noisy. A high R² with a patterned residual plot means the model is wrong in a way you can fix.

Similar Topics