Seaborn pairplot: Plot Pairwise Relationships

Use sns.pairplot to plot every pair of numeric columns at once: pick variables, color by group, show only the lower triangle, change the plot kind and size, and customize it with PairGrid.

sns.pairplot(df) draws a grid of scatter plots for every pair of numeric columns in a DataFrame, with each column's distribution on the diagonal. Pass hue= to color by group, vars= to choose columns, and corner=True to drop the mirrored upper half.

Quick Example

The data is the wine recognition set bundled with scikit-learn: lab measurements of 178 Italian wines from three grape cultivars.

import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.datasets import load_wine

wine = load_wine(as_frame=True).frame
wine["cultivar"] = wine.pop("target").map({0: "A", 1: "B", 2: "C"})

cols = ["alcohol", "flavanoids", "color_intensity", "proline"]
colors = {"A": "#9f1239", "B": "#d4a017", "C": "#0f766e"}

sns.set_theme(style="ticks")
g = sns.pairplot(wine, vars=cols, hue="cultivar", palette=colors,
                 corner=True, height=2.1, plot_kws={"s": 22, "alpha": 0.8})
g.figure.suptitle("Wine chemistry by cultivar", y=1.02)
plt.show()

Lower-triangle Seaborn pairplot of alcohol, flavanoids, color intensity, and proline, with the three wine cultivars in red, gold, and teal forming mostly separate clusters

Cultivar A has the highest proline, B is lowest in color intensity, and C is low in flavanoids. The flavanoids and color intensity panel separates the three groups with little overlap. The code targets Seaborn 0.13.

Choose Which Columns to Plot

By default, pairplot uses every numeric column. This DataFrame has 13, which would make 169 panels. Pass vars= with the few you care about, or use x_vars= and y_vars= for a rectangle, such as several features against one outcome.

sns.pairplot(wine, x_vars=["flavanoids", "color_intensity", "malic_acid"],
             y_vars=["alcohol"], hue="cultivar", palette=colors, height=3)
plt.show()

One row of three scatter plots showing alcohol against flavanoids, color intensity, and malic acid, colored by cultivar

Numeric ID columns and integer-coded categories count as numeric, so drop or relabel them first. That's why the Quick Example turns target into text.

Change the Plot Kind

kind controls the off-diagonal panels ("scatter", "reg", "kde", or "hist"), and diag_kind controls the diagonal ("hist", "kde", or None). With hue, the diagonal defaults to density curves. Without it, it defaults to histograms.

Add Regression Lines

sns.pairplot(wine, vars=cols[:3], kind="reg", height=2.3,
             plot_kws={"line_kws": {"color": "#be123c"},
                       "scatter_kws": {"s": 14, "color": "#475569", "alpha": 0.6}},
             diag_kws={"color": "#94a3b8"})
plt.show()

Three by three pairplot with gray points, red regression lines, and gray histograms on the diagonal

The settings for regplot go inside plot_kws. Pooled lines can mislead when groups differ, so compare them with a hue version.

KDE Pairplot

sns.pairplot(wine, vars=cols[:3], hue="cultivar", palette=colors, kind="kde",
             corner=True, height=2.3, plot_kws={"levels": 4})
plt.show()

Corner pairplot of density contours for each wine cultivar

plot_kws is passed to the off-diagonal function and diag_kws to the diagonal one. Here levels goes to kdeplot.

Set the Size of a pairplot

pairplot is a figure-level function, so plt.figure(figsize=...) has no effect on it. Set height (inches per panel, 2.5 by default) and aspect (width divided by height). A grid of four variables at height=2.1 is about 8.4 inches tall, plus room for the legend on the side.

g = sns.pairplot(wine, vars=cols[:3], height=1.6, aspect=1.4)
print(g.figure.get_size_inches())

This prints [6.72 4.8 ]: three panels of 1.6 × 1.4 inches across, and three of 1.6 inches down. To resize a finished grid instead:

g.figure.set_size_inches(9, 6)  # or resize the finished figure

Move the Legend

pairplot places the legend outside the grid. With corner=True there is empty space in the upper right, so move it there with sns.move_legend():

g = sns.pairplot(wine, vars=cols[:3], hue="cultivar", palette=colors,
                 corner=True, height=2.2)
sns.move_legend(g, "center", bbox_to_anchor=(0.68, 0.72), title="Cultivar", frameon=True)
plt.show()

Corner pairplot with the cultivar legend placed in the empty upper right area

See how to move a Seaborn legend for the other positions.

Add Correlations with PairGrid

pairplot is a shortcut for sns.PairGrid. Use PairGrid when each region needs its own function, for example scatter plots below, correlation values above, and histograms on the diagonal.

def corr_label(x, y, **kwargs):
    r = x.corr(y)
    ax = plt.gca()
    ax.set_facecolor(plt.cm.RdBu_r((r + 1) / 2, alpha=0.55))
    ax.annotate(f"r = {r:.2f}", (0.5, 0.5), xycoords="axes fraction",
                ha="center", va="center", fontsize=14)

g = sns.PairGrid(wine, vars=cols, height=2)
g.map_lower(sns.scatterplot, s=14, color="#334155", alpha=0.6)
g.map_diag(sns.histplot, color="#64748b")
g.map_upper(corr_label)
plt.show()

PairGrid with scatter plots below the diagonal, histograms on it, and shaded correlation coefficients above it

The strongest of these pooled correlations is between alcohol and proline, at 0.64. For a grid of coefficients alone, a Seaborn correlation heatmap handles many more columns.

Practical Tips

  • Large datasets make pairplot slow and overplotted. Plot a sample (wine.sample(100, random_state=0)) or use kind="hist".
  • Missing values are dropped panel by panel. Pass dropna=True to drop incomplete rows from the whole grid.
  • pairplot returns a PairGrid. Save it with g.savefig("pairs.png", dpi=200).
  • g.axes[row, col] reaches a single panel. With corner=True, the upper entries are None.
  • For long tick labels, see rotating labels on FacetGrid and pairplot.

Similar Topics