Regression plots: regplot and lmplot

seaborn · Practical · 10 min

A quick visual fit shows whether a relationship is roughly linear, curved or driven by outliers before you model it formally.

sns.regplot(data=df, x=..., y=...) draws a scatter plot plus a fitted linear regression line with a 95% bootstrap confidence band for the line. sns.lmplot is the figure-level version with hue, col and row, so you can fit one line per group or per panel.

Options change the model:

  • order=2 fits a polynomial;
  • logistic=True fits a logistic regression for a 0/1 outcome (needs statsmodels);
  • robust=True down-weights outliers (needs statsmodels);
  • lowess=True draws a nonparametric smooth curve (needs statsmodels);
  • ci=None removes the band, which is faster with lots of data;
  • x_bins=10 or x_estimator=np.mean summarize a discrete or crowded x.

residplot plots the residuals of the fit; a visible pattern means the straight-line model is missing structure.

These functions are for visualization: they do not return the slope, intercept or p-values. Fit the model with numpy.polyfit, scikit-learn or statsmodels when you need numbers, and make sure the plot shows the same model you report.

A band that looks narrow does not mean predictions are precise: it is the uncertainty of the mean line, not of individual points. Individual observations scatter much more widely, which the points themselves show.

Example

import matplotlib
matplotlib.use("Agg")
import seaborn as sns
import pandas as pd
import numpy as np

rng = np.random.default_rng(6)
df = pd.DataFrame({"ads": rng.uniform(0, 10, 80)})
df["sales"] = 5 + 2.0 * df["ads"] + rng.normal(0, 3, 80)
df["store"] = rng.choice(["mall", "street"], 80)

ax = sns.regplot(data=df, x="ads", y="sales", ci=95, seed=0,
                 scatter_kws={"alpha": 0.5})
slope, intercept = np.polyfit(df["ads"], df["sales"], 1)   # numbers come from you
print(round(slope, 1), round(intercept, 1))  # 2.0 4.8 (true: 2 and 5)
print(len(ax.collections))                   # 2: scatter points + CI band
ax.figure.savefig("reg.png")

g = sns.lmplot(data=df, x="ads", y="sales", hue="store", height=3)
g.savefig("reg_by_store.png")

Remember

  • regplot/lmplot draw a fit with a confidence band for the mean line
  • order, logistic, robust and lowess change the fitted model
  • They do not return coefficients; fit the model separately for numbers

Watch out for

  • Reading the narrow confidence band as the range where individual points will fall.

Check yourself

  1. What does the shaded band around a regplot line represent?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: seaborn.pydata.org/tutorial/regression.html

Builds on

Unlocks

Nothing builds on this yet.