Seaborn regplot and lmplot: Regression Lines

Add a regression line to a scatter plot with sns.regplot, split it by group with sns.lmplot, fit curves, handle outliers and yes/no outcomes, and get the slope and intercept.

sns.regplot(data=df, x="x", y="y") draws a scatter plot with a linear regression line and a 95% confidence band. sns.lmplot() does the same as a figure-level plot, so it can fit separate lines with hue= and split them into panels with col=.

Quick Example

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

# Sample data: 160 used car listings
rng = np.random.default_rng(63)
n = 160
cars = pd.DataFrame({
    "mileage": rng.uniform(5, 160, n).round(),  # thousand km
    "fuel": rng.choice(["Petrol", "Diesel", "Hybrid"], n),
})
new_price = cars["fuel"].map({"Petrol": 24, "Diesel": 25.5, "Hybrid": 30})
cars["price"] = (new_price * np.exp(-cars["mileage"] / 110)
                 + rng.normal(0, 1.3, n)).round(1)  # $ thousands

sns.set_theme(style="darkgrid")
fig, ax = plt.subplots(figsize=(8, 4.8))
sns.regplot(data=cars, x="mileage", y="price", seed=1,
            scatter_kws={"color": "#475569", "alpha": 0.6, "s": 28},
            line_kws={"color": "#e11d48", "linewidth": 2.5}, ax=ax)
ax.set(title="Used car price vs mileage", xlabel="Mileage (thousand km)",
       ylabel="Price ($ thousands)")
plt.show()

Seaborn regplot of used car price against mileage with a red downward regression line and a shaded confidence band

The price falls as mileage rises, and the points bend away from the straight line at both ends. We'll fit that curve below. The code targets Seaborn 0.13.

regplot vs lmplot

regplot lmplot
Level Axes-level Figure-level
Returns A Matplotlib Axes A FacetGrid
Accepts ax= Yes No
hue, col, row No Yes
Size figsize on your figure height and aspect
data Optional (arrays work) Required

Use regplot for one fit, especially inside a subplot layout. Use lmplot to compare fits across categories. The figure-level vs axes-level guide covers the difference across Seaborn.

Separate Lines by Group with lmplot

colors = {"Petrol": "#f59e0b", "Diesel": "#334155", "Hybrid": "#10b981"}

g = sns.lmplot(data=cars, x="mileage", y="price", hue="fuel", palette=colors,
               markers=["o", "s", "D"], height=4.5, aspect=1.5, seed=1,
               scatter_kws={"alpha": 0.6, "s": 24})
g.set_axis_labels("Mileage (thousand km)", "Price ($ thousands)")
plt.show()

Seaborn lmplot with separate regression lines for petrol, diesel, and hybrid cars, with the hybrid line highest

Add col="fuel" to give each group its own panel. Panels share axes by default, and facet_kws={"sharey": False} turns that off.

g = sns.lmplot(data=cars, x="mileage", y="price", col="fuel", hue="fuel",
               palette=colors, height=3.4, aspect=1, seed=1, legend=False)
g.set_titles("{col_name}")
plt.show()

Three side-by-side regression plots of price against mileage, one per fuel type, on shared axes

Fit a Curve with order, logx, or lowess

A straight line is only one option:

  • order=2 fits a polynomial of that degree.
  • lowess=True fits a locally weighted curve that follows the data without a formula. It requires statsmodels and draws no confidence band.
  • logx=True fits y against log(x) and needs positive x values. It suits curves that rise or fall quickly and then level off.
fig, axes = plt.subplots(1, 3, figsize=(11, 3.6), sharey=True)
fits = {"Linear": {}, "order=2": {"order": 2}, "lowess=True": {"lowess": True}}
for ax, (title, kwargs) in zip(axes, fits.items()):
    sns.regplot(data=cars, x="mileage", y="price", seed=1,
                scatter_kws={"color": "#94a3b8", "s": 14},
                line_kws={"color": "#7c3aed"}, ax=ax, **kwargs)
    ax.set_title(title)
plt.show()

Three fits to the car data: a straight line, a second-order polynomial, and a lowess curve, with the last two following the bend

Pick one of order, lowess, logx, robust, or logistic. Combining them raises ValueError: Mutually exclusive regression options.

Check the Fit with a Residual Plot

sns.residplot() plots what's left after the fit. A good model leaves a shapeless band around zero.

fig, axes = plt.subplots(1, 2, figsize=(11, 3.6), sharey=True)
for ax, order in zip(axes, [1, 2]):
    sns.residplot(data=cars, x="mileage", y="price", order=order,
                  color="#0f766e", ax=ax)
    ax.set(title=f"Residuals, order={order}", ylabel="Residual")
plt.show()

Residual plots for the linear fit, which curve in a U shape, and for the second-order fit, which scatter evenly around zero

Change or Remove the Confidence Band

The band is a bootstrap confidence interval for the fitted line, not a range where new points should fall. ci sets its level and ci=None removes it, which also makes large datasets plot faster. seed makes the bootstrap repeatable.

sns.regplot(data=cars, x="mileage", y="price", ci=99, seed=1)
sns.regplot(data=cars, x="mileage", y="price", ci=None)

Note that regplot still uses ci. The errorbar parameter from lineplot and barplot isn't available here.

Handle Outliers with robust=True

Ordinary least squares gets pulled toward extreme points. robust=True downweights them (it uses statsmodels).

listings = cars.copy()
high = listings["mileage"].nlargest(6).index
listings.loc[high, "price"] += 18  # a few collector cars

fig, ax = plt.subplots(figsize=(8, 4.5))
sns.regplot(data=listings, x="mileage", y="price", ci=None,
            scatter_kws={"color": "#64748b", "s": 20},
            line_kws={"color": "#e11d48", "label": "Least squares"}, ax=ax)
sns.regplot(data=listings, x="mileage", y="price", ci=None, label="robust=True",
            robust=True, scatter=False, line_kws={"color": "#2563eb"}, ax=ax)
ax.legend(loc="lower left")
plt.show()

Scatter plot with six high-priced outliers, where the least squares line is flatter than the robust regression line

Logistic Regression for Yes/No Outcomes

With a 0/1 column as y, logistic=True fits a probability curve. y_jitter spreads the points vertically for display without changing the fit. Lowering n_boot speeds up the band.

value = cars["price"] / (new_price * np.exp(-cars["mileage"] / 110))
cars["sold_in_30_days"] = (rng.random(n) < 1 / (1 + np.exp(14 * (value - 1)))).astype(int)
cars["price_vs_market"] = (value - 1).mul(100).round(1)

fig, ax = plt.subplots(figsize=(8, 4.5))
sns.regplot(data=cars, x="price_vs_market", y="sold_in_30_days", logistic=True,
            y_jitter=0.03, n_boot=300, seed=1, scatter_kws={"alpha": 0.5, "s": 22},
            line_kws={"color": "#c2410c"}, ax=ax)
ax.set(xlabel="Asking price vs market (%)", ylabel="Probability of selling in 30 days")
plt.show()

Logistic regression curve showing the probability of a sale within 30 days falling as the asking price rises above market

The y column has to be numeric. Map text such as "yes" and "no" to 1 and 0 first.

Summarize Dense Data with x_bins

x_bins replaces the cloud of points with the mean and confidence interval in each bin. The line is still fitted to the original data.

fig, ax = plt.subplots(figsize=(8, 4.5))
sns.regplot(data=cars, x="mileage", y="price", x_bins=10, order=2, seed=1,
            color="#0369a1", ax=ax)
plt.show()

Ten binned means with error bars over mileage, with a curved fit passing close to each

Get the Slope and Intercept

Seaborn doesn't return the fitted coefficients or statistics such as R². Compute them with SciPy, then add them to the chart:

from scipy import stats

fit = stats.linregress(cars["mileage"], cars["price"])
label = f"price = {fit.intercept:.1f} - {-fit.slope:.3f} × mileage\nR² = {fit.rvalue**2:.2f}"
print(label)

fig, ax = plt.subplots(figsize=(8, 4.5))
sns.regplot(data=cars, x="mileage", y="price", seed=1, color="#475569", ax=ax)
ax.text(0.97, 0.95, label, transform=ax.transAxes, ha="right", va="top",
        bbox={"facecolor": "white", "edgecolor": "none"})
plt.show()

Regression plot with the equation of the line and R squared written in the upper right corner

For standard errors, several predictors, or model summaries, fit the model with statsmodels and plot its predictions.

Similar Topics