Pandas scatter_matrix: Plot Every Pair of Columns

Compare all numeric columns at once with pandas scatter_matrix: KDE diagonals, colors by category, readable labels, correlations, and a lower-triangle layout.

pandas.plotting.scatter_matrix(df) draws a scatter plot for every pair of numeric columns in a DataFrame, with a histogram of each column on the diagonal.

Quick Example

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pandas.plotting import scatter_matrix

rng = np.random.default_rng(149)

# 300 made-up used car listings.
n = 300
fuel = rng.choice(["Petrol", "Diesel", "Electric"], size=n, p=[0.5, 0.3, 0.2])
electric = fuel == "Electric"
age = np.where(electric, rng.uniform(0.5, 6, n), rng.uniform(0.5, 12, n))
yearly = pd.Series(fuel).map({"Petrol": 12, "Diesel": 19, "Electric": 11}).to_numpy()
mileage = age * yearly * rng.gamma(14, 1 / 14, n)
power = rng.normal(100, 22, n) + 45 * electric
new_price = 9000 + 190 * power + 6000 * electric
price = new_price * np.exp(-0.11 * age - 0.0012 * mileage) * rng.normal(1, 0.07, n)

cars = pd.DataFrame({"age": age, "mileage": mileage, "power": power,
                     "price": price / 1000, "fuel": fuel})
cols = ["age", "mileage", "power", "price"]

scatter_matrix(cars[cols], figsize=(8, 8), alpha=0.6,
               hist_kwds={"bins": 20, "edgecolor": "white"})
plt.suptitle("Used Car Listings", y=0.93)
plt.show()

Four by four scatter matrix of car age, mileage, power, and price, with histograms on the diagonal

Age is in years, mileage in thousands of kilometers, power in kilowatts, and price in thousands. The code targets pandas 3.

How to Read a Scatter Matrix

Each row shares a y variable and each column shares an x variable. The panel in the price row and age column plots price against age, and the panel mirrored across the diagonal shows the same points with the axes swapped.

The y-axis numbers beside the top-left histogram are values of the first column, not counts. They line up with the scatter plots in that row.

Compare the shapes with the correlation coefficients:

print(cars[cols].corr().round(2))

Age and mileage rise together (0.82), and both go with lower prices. More power goes with higher prices (0.61), a looser relationship that shows as a wider cloud.

Choose Numeric Columns

scatter_matrix() skips text columns. A boolean column is treated as numeric and then fails with a TypeError that begins numpy boolean subtract. Select the columns you want, or filter by type:

numbers = cars.select_dtypes("number")  # leaves out text and boolean columns
print(numbers.columns.tolist())

To include a boolean column, convert it first with .astype(int). Missing values are dropped separately for each panel, so one gap doesn't remove the whole row everywhere.

Show KDE Curves on the Diagonal

Set diagonal="kde" to draw smooth density curves instead of histograms. This needs SciPy.

scatter_matrix(cars[["age", "mileage", "price"]], figsize=(7, 7), diagonal="kde",
               color="#2a9d8f", alpha=0.7, s=18,
               density_kwds={"color": "#264653", "linewidth": 2})
plt.show()

Scatter matrix of age, mileage, and price with density curves on the diagonal

Other keyword arguments, such as s for point size and color, go to Matplotlib's scatter(). Style the diagonal with density_kwds or hist_kwds.

Color Points by a Category

There's no hue argument. Pass c a list with one color per row, and build the legend yourself.

from matplotlib.lines import Line2D

colors = {"Petrol": "#e76f51", "Diesel": "#6c757d", "Electric": "#3a86ff"}

axes = scatter_matrix(cars[cols], figsize=(8, 8), c=cars["fuel"].map(colors),
                      alpha=0.7, s=16,
                      hist_kwds={"bins": 20, "color": "#ced4da"})

handles = [Line2D([], [], marker="o", linestyle="", color=color, label=name)
           for name, color in colors.items()]
fig = axes[0, 0].figure
fig.legend(handles=handles, loc="upper center", ncols=3,
           bbox_to_anchor=(0.5, 0.94), frameon=False)
plt.show()

Scatter matrix with petrol, diesel, and electric cars in different colors, electric cars newer and more powerful

The colors apply to the scatter plots only. The diagonal shows all rows together.

Make Long Labels Readable

scatter_matrix() returns a 2D array of Axes, so you can change any label or tick. Loop over axes.flat:

long_names = cars[cols].rename(columns={
    "age": "Age (years)", "mileage": "Mileage (000 km)",
    "power": "Power (kW)", "price": "Price (000)"})

axes = scatter_matrix(long_names, figsize=(8, 8), color="#7b2cbf", alpha=0.5,
                      hist_kwds={"bins": 20})

for ax in axes.flat:
    ax.xaxis.label.set(rotation=0, fontsize=11, fontweight="bold")
    ax.yaxis.label.set(fontsize=11, fontweight="bold")
    ax.tick_params(axis="x", labelrotation=0)
plt.show()

Scatter matrix with descriptive bold axis labels and horizontal tick labels

By default the x tick labels are rotated 90 degrees. For labels that still collide, increase figsize or rotate the y labels with rotation=45, ha="right".

Show Correlations in the Upper Triangle

The upper triangle repeats the lower one, so you can replace it with the correlation of each pair. np.triu_indices_from(axes, k=1) gives the positions above the diagonal.

axes = scatter_matrix(cars[cols], figsize=(8, 8), color="#457b9d", alpha=0.6,
                      hist_kwds={"bins": 20})
corr = cars[cols].corr()

for i, j in zip(*np.triu_indices_from(axes, k=1)):
    ax = axes[i, j]
    r = corr.iloc[i, j]
    for points in ax.collections:
        points.set_visible(False)
    ax.set_facecolor(plt.cm.RdBu_r((r + 1) / 2))
    ax.text(0.5, 0.5, f"{r:.2f}", transform=ax.transAxes, ha="center",
            va="center", fontsize=18,
            color="white" if abs(r) > 0.6 else "black")
plt.show()

Scatter matrix with scatter plots below the diagonal and colored correlation values above it

Pearson correlation measures straight-line association. Keep the scatter plots visible, because curves and clusters can hide behind a single number.

Show Only the Lower Triangle

To remove the repeated panels entirely, hide those Axes.

axes = scatter_matrix(cars[cols], figsize=(8, 8), color="#bc4749", alpha=0.5,
                      hist_kwds={"bins": 20})
for i, j in zip(*np.triu_indices_from(axes, k=1)):
    axes[i, j].set_visible(False)

axes[0, 0].figure.savefig("scatter-matrix.png", dpi=200, bbox_inches="tight")
plt.show()

Scatter matrix showing only the diagonal histograms and the panels below them

scatter_matrix or seaborn pairplot?

Function Color by category Best for
pandas.plotting.scatter_matrix() Manual, with c= A quick look with no extra library
seaborn.pairplot() hue= with a legend Group comparisons and corner=True layouts
plotly.express.scatter_matrix() color= with a legend Hovering over points and linked selection

With Seaborn, the colored version takes one line: sns.pairplot(cars, hue="fuel", corner=True). See the seaborn pairplot guide.

Practical Tips

  • Stick to about six columns. The number of panels grows with the square of the column count.
  • For many columns, start with a correlation matrix heatmap and then plot the interesting ones.
  • With thousands of rows, lower alpha, set a small s, or plot a sample such as df.sample(2000, random_state=0).
  • range_padding controls the blank space around the data in each panel. The default is 0.05.

Similar Topics