Compute the correlation matrix via corr = df.corr(numeric_only=True) and render an annotated heatmap either with seaborn.heatmap(corr, annot=True, fmt=".2f", cmap="coolwarm", vmin=-1, vmax=1) (recommended for publication-ready labels, masking, and centered colorbars) or using pure Matplotlib via ax.imshow(corr, cmap="coolwarm", vmin=-1, vmax=1) when avoiding third-party plotting dependencies beyond Pandas and Matplotlib.
Basic Example
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
df = pd.DataFrame({
"age": [25, 32, 47, 51, 62, 38],
"salary": [48000, 62000, 91000, 95000, 112000, 74000],
"experience": [2, 7, 20, 24, 35, 13],
"city": ["Lahore", "Karachi", "Lahore", "Islamabad", "Karachi", "Lahore"],
})
# 1. Compute pairwise Pearson correlation matrix (pass `numeric_only=True` to skip string columns)
corr = df.corr(numeric_only=True)
# 2. Recommended: Plot annotated heatmap with Seaborn + Matplotlib
fig, ax = plt.subplots(figsize=(6, 5), layout="constrained")
sns.heatmap(
corr,
annot=True, # Display correlation coefficients inside each cell
fmt=".2f", # Format values to 2 decimal places
cmap="coolwarm", # Diverging colormap centered at 0
vmin=-1, # Anchor color scale strictly to [-1, 1]
vmax=1,
center=0,
square=True, # Keep cells square
linewidths=0.5, # Thin gridlines between cells
cbar_kws={"shrink": 0.8, "label": "Pearson r"},
ax=ax,
)
ax.set_title("Feature Correlation Matrix")
plt.show()
Key Details & Edge Cases
- Always pass
numeric_only=Truein Pandas 2.0+ (df.corr(numeric_only=True)):- Since Pandas 2.0,
df.corr()defaults tonumeric_only=Falseand raisesValueError: could not convert string to floatwhenever the DataFrame contains any text or categorical columns. Passingnumeric_only=True(or selecting columns explicitly viadf[["a", "b", "c"]].corr()) prevents this crash.
- Since Pandas 2.0,
- Anchor
vmin=-1andvmax=1with a diverging colormap ("coolwarm","RdBu_r","vlag"):- Without
vmin=-1, vmax=1, Seaborn/Matplotlib auto-scales colors to the min/max values incorr(e.g.,[0.72, 1.0]), making a moderate+0.72correlation look like-1.0deep blue. Always fixvmin=-1, vmax=1, center=0so0is neutral white/gray and±1are symmetric extremes.
- Without
- Hiding the redundant upper triangle (
mask=np.triu(np.ones_like(corr, dtype=bool))):- Because correlation matrices are symmetric ($r_{ij} = r_{ji}$) with
1.00along the diagonal, mask the upper triangle in Seaborn to cut visual clutter in half:import numpy as np mask = np.triu(np.ones_like(corr, dtype=bool)) sns.heatmap(corr, mask=mask, annot=True, fmt=".2f", cmap="coolwarm", vmin=-1, vmax=1)
- Because correlation matrices are symmetric ($r_{ij} = r_{ji}$) with
- Choosing the right correlation method (
method="pearson" | "spearman" | "kendall"):"pearson"(default) measures linear correlation and is sensitive to outliers."spearman"measures monotonic rank correlation (handles skewed distributions, ordinal scales, and non-linear monotonic curves)."kendall"measures ordinal rank concordance (more robust on small sample sizes with ties).
- Zero-Seaborn alternative using pure Matplotlib + Pandas (
ax.imshow):- If Seaborn is not installed, render the matrix directly with Matplotlib:
fig, ax = plt.subplots(figsize=(6, 5), layout="constrained") im = ax.imshow(corr, cmap="coolwarm", vmin=-1, vmax=1) ax.set_xticks(range(len(corr.columns)), labels=corr.columns, rotation=45, ha="right") ax.set_yticks(range(len(corr.index)), labels=corr.index) for i in range(len(corr.index)): for j in range(len(corr.columns)): ax.text(j, i, f"{corr.iloc[i, j]:.2f}", ha="center", va="center", color="black") fig.colorbar(im, ax=ax, shrink=0.8) plt.show()
- If Seaborn is not installed, render the matrix directly with Matplotlib:
- Constant (zero-variance) columns produce
NaNrows/columns:- If a numeric column has identical values in every row (standard deviation
0), division by zero producesNaNacross its row and column indf.corr(). Drop zero-variance columns beforehand viadf = df.loc[:, df.nunique() > 1].
- If a numeric column has identical values in every row (standard deviation
Comparison of Correlation Heatmap Plotting Methods in Python
| Approach | Built-In Cell Value Annotations? | Easy Upper-Triangle Masking? | Extra Dependencies | Best Used When |
|---|---|---|---|---|
df.corr(numeric_only=True) + sns.heatmap(..., annot=True) (Recommended) |
Yes (annot=True, fmt=".2f" with auto text contrast) |
Yes (mask=np.triu(...)) |
seaborn, matplotlib |
Exploratory data analysis (EDA), papers, and dashboards needing clean, readable annotations. |
df.corr(numeric_only=True) + ax.imshow() |
Manual (requires nested ax.text() loop) |
Manual (requires masking array with np.ma.masked_where) |
matplotlib only |
Restricted environments where seaborn is not installed. |
corr.style.background_gradient(cmap="coolwarm", vmin=-1, vmax=1) |
Yes (renders HTML table directly) | No | matplotlib (for colormap) |
Interactive Jupyter Notebooks where a quick, copyable HTML table is preferred over a static image. |
You must log in or register to comment.
