Python for Data Analytics & AutomationLesson 31 of 41
Lesson 31 of 41

Multivariate EDA: Correlation Heatmaps, Pairplots & FacetGrid

Overview & Learning Objectives

Multivariate exploratory data analysis (EDA) uncovers hidden interactions, collinearity, and predictive signals across multiple features simultaneously. Bivariate correlation matrices quantify linear or monotonic relationships, while Seaborn heatmaps with diverging color palettes make strong correlations instantly noticeable. For high-dimensional datasets, `sns.pairplot()` and `sns.FacetGrid` display pairwise distributions and multi-panel categorical slices.

  • Calculate Pearson and Spearman rank correlation matrices across numerical DataFrame features.
  • Render publication-grade correlation heatmaps with masks, annotations, and diverging colormaps.
  • Deploy `sns.pairplot()` and `FacetGrid` to explore pairwise interactions segmented by categorical classes.

Industry Standard

Standard: Machine learning engineers at Netflix and Google perform correlation matrix screening before model training to eliminate multicollinear features (variance inflation factor > 5).

Real-World Example: ScoopCraft Dark-Store Delivery Metric Correlation Matrix

ScoopCraft data scientists analyze correlations between basket size, distance, weather rain index, driver tip, and delivery time.

Feature PairPearson (r)Spearman (rho)Relationship Interpretation
Delivery_Min vs Distance_Km+0.84+0.88Strong positive linear correlation
Delivery_Min vs Rain_Index+0.62+0.65Moderate positive relationship
Tip_Amount vs Basket_Size+0.71+0.74Strong positive correlation with basket value
Rating vs Delivery_Min-0.58-0.62Moderate negative correlation (delays harm rating)

Syntax & Core Code Implementation

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

# Compute correlation matrix
corr = df[['basket_spend', 'delivery_min', 'distance_km', 'tip_amount', 'rating']].corr(method='pearson')

# Generate diagonal mask to hide redundant upper triangle
mask = np.triu(np.ones_like(corr, dtype=bool))

fig, ax = plt.subplots(figsize=(9, 7), dpi=150)
sns.heatmap(
    corr,
    mask=mask,
    annot=True,
    fmt='.2f',
    cmap='coolwarm',
    vmin=-1,
    vmax=1,
    center=0,
    linewidths=0.5,
    cbar_kws={'label': 'Pearson Correlation (r)'},
    ax=ax
)
ax.set_title('Multivariate Correlation Heatmap', fontsize=14, fontweight='bold')
plt.show()

Parameters & Arguments Breakdown

  • method: Correlation method: pearson measures linear relationship; spearman measures monotonic rank relationship.
  • mask: Array indicating which cells should not be rendered (used to hide redundant upper symmetric triangle).
  • annot=True: Prints numerical correlation coefficient inside each heatmap cell.
  • cmap="coolwarm": Diverging colormap anchored at zero (negative=cool/blue, positive=warm/red).

Step-by-Step Implementation

  1. Subset Numerical Features: Isolate numeric columns using `df.select_dtypes(include=[np.number])`.
  2. Compute Masked Correlation Matrix: Compute `.corr()` and generate upper triangle mask via `np.triu()`.
  3. Inspect Pairwise Scatterplots: Use `sns.pairplot(df, hue="customer_tier", corner=True)` to inspect non-linear scatter relationships.

Common Mistakes & Limitations

  • Assuming zero Pearson correlation means no relationship exists (variables may have a strong non-linear quadratic or circular relationship).
  • Showing both upper and lower triangles of a correlation heatmap, which creates redundant visual clutter.
  • Running `sns.pairplot()` on large DataFrames with dozens of numeric columns, causing the kernel to freeze for minutes.

Keyboard Shortcuts (Jupyter & VS Code)

ActionWindowsMac
Comment highlighted EDA code blockCtrl + K, Ctrl + CCmd + K, Cmd + C

Pro Tips & Modern Best Practices

  • Use `method="spearman"` instead of Pearson when data contains extreme outliers or non-normally distributed ordinal ranks.
  • Pass `corner=True` to `sns.pairplot()` to automatically omit the upper symmetric half of the pairwise grid.