How do you compute and plot a correlation matrix heatmap using Pandas? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

How do you compute and plot a correlation matrix heatmap using Pandas?

message-square
0

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=True in Pandas 2.0+ (df.corr(numeric_only=True)):
    • Since Pandas 2.0, df.corr() defaults to numeric_only=False and raises ValueError: could not convert string to float whenever the DataFrame contains any text or categorical columns. Passing numeric_only=True (or selecting columns explicitly via df[["a", "b", "c"]].corr()) prevents this crash.
  • Anchor vmin=-1 and vmax=1 with a diverging colormap ("coolwarm", "RdBu_r", "vlag"):
    • Without vmin=-1, vmax=1, Seaborn/Matplotlib auto-scales colors to the min/max values in corr (e.g., [0.72, 1.0]), making a moderate +0.72 correlation look like -1.0 deep blue. Always fix vmin=-1, vmax=1, center=0 so 0 is neutral white/gray and ±1 are symmetric extremes.
  • 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.00 along 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)
      
  • 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()
      
  • Constant (zero-variance) columns produce NaN rows/columns:
    • If a numeric column has identical values in every row (standard deviation 0), division by zero produces NaN across its row and column in df.corr(). Drop zero-variance columns beforehand via df = df.loc[:, df.nunique() > 1].

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.