TExcelTAD
Home › Data Science › DS Correlation Matrix

DS Correlation Matrix

With more than two variables, computing correlations pair by pair gets tedious. A correlation matrix shows the correlation of every variable with every other in one table. It is one of the first things to look at in a new dataset.

Building the matrix

DataFrame.corr() computes Pearson correlations between all numeric columns. We drop the date column first, because dates aren't numbers you can correlate:

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

corr = bikes.drop(columns="date").corr()
print(corr.round(2))
          temp_c  rain_mm  humidity  weekend  rides
temp_c      1.00    -0.07      0.05     0.18   0.85
rain_mm    -0.07     1.00     -0.06    -0.08  -0.41
humidity    0.05    -0.06      1.00     0.06   0.06
weekend     0.18    -0.08      0.06     1.00   0.43
rides       0.85    -0.41      0.06     0.43   1.00

Reading the matrix

  • The diagonal is always 1.00: every variable correlates perfectly with itself.
  • The matrix is symmetric: corr(temp, rides) equals corr(rides, temp), so you only need to read one triangle.
  • The rides row (or column) is the most interesting one: it shows how each candidate predictor relates to the variable we want to explain.

Rides correlate strongly with temperature (0.85), moderately with weekend (0.43), negatively with rain (−0.41), and hardly at all with humidity (0.06). Among the predictors themselves, all correlations are small — that's good news for regression, because predictors that are strongly correlated with each other make their individual effects hard to separate (a problem called multicollinearity).

Ranking the predictors

To focus on the target, pull out its column and sort by absolute value — a strong negative relationship is just as informative as a strong positive one:

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

target = bikes.drop(columns="date").corr()["rides"].drop("rides")
ranking = target.reindex(target.abs().sort_values(ascending=False).index)
print(ranking.round(3))
temp_c      0.852
weekend     0.432
rain_mm    -0.410
humidity    0.059
Name: rides, dtype: float64

Visualising it as a heatmap

A table of numbers is hard to scan. A heatmap colours each cell by its value. A diverging colour map (blue for negative, red for positive, white for zero) with the scale fixed from −1 to 1 makes the strength and sign visible at once:

python · try it yourself
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

corr = bikes.drop(columns="date").corr()
fig, ax = plt.subplots(figsize=(6, 5))
im = ax.imshow(corr, cmap="RdBu_r", vmin=-1, vmax=1)
ax.set_xticks(range(len(corr)), corr.columns, rotation=45)
ax.set_yticks(range(len(corr)), corr.columns)
for i in range(len(corr)):
    for j in range(len(corr)):
        v = corr.iloc[i, j]
        ax.text(j, i, f"{v:.2f}", ha="center", va="center", fontsize=9,
                color="white" if abs(v) > 0.6 else "black")
fig.colorbar(im)
ax.set_title("Riverside Bikes correlation matrix")
plt.tight_layout()
plt.show()
print("Heatmap of a", corr.shape, "correlation matrix")
Heatmap of a (5, 5) correlation matrix

In the Visualization with seaborn lesson you'll draw the same chart with a single sns.heatmap(...) call.

A note on many variables

With 20 columns a matrix has 190 distinct pairs. Some will show a moderate correlation purely by chance. Treat a correlation matrix as a map of where to look more closely, not as a list of discoveries.

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(0)
noise = pd.DataFrame(rng.normal(size=(30, 20)))   # 20 columns of pure noise
c = noise.corr().to_numpy()
pairs = c[np.triu_indices(20, k=1)]               # upper triangle, no diagonal

print("pairs:", len(pairs))
print("largest |r| among unrelated columns:", np.abs(pairs).max().round(2))
print("pairs with |r| > 0.4:", (np.abs(pairs) > 0.4).sum())
pairs: 190
largest |r| among unrelated columns: 0.54
pairs with |r| > 0.4: 2

None of these columns is related to any other, yet some pairs look moderately correlated. More data and a clear prior hypothesis are the cure.

Test yourself

Why are all diagonal entries of a correlation matrix equal to 1?

  1. They are rounded
  2. Each variable is perfectly correlated with itself
  3. pandas sets them to 1 to mark missing values
  4. Because the data is normalised

Why sort predictors by the **absolute** value of their correlation with the target?

  1. Negative correlations are errors
  2. A strong negative relationship is as informative as a strong positive one
  3. pandas can't sort negative numbers
  4. It makes the heatmap red

You compute a 20-column correlation matrix and find one pair with r = 0.45. What should you conclude?

  1. The two variables are definitely related
  2. It might be chance — with many pairs some moderate correlations appear by accident
  3. One variable causes the other
  4. The matrix is wrong