Heatmap
Python · Data Visualization
Theory
A heatmap shows a table of numbers as a grid of coloured cells, so large and small values stand out by colour. Its most common use in data work is the correlation matrix: df.corr() gives the Pearson correlation between every pair of numeric columns, from -1 (move in opposite directions) through 0 (no straight-line relationship) to 1 (move together), and the diagonal is always 1.
In matplotlib, ax.imshow(corr, cmap='RdBu_r', vmin=-1, vmax=1) colours the grid; fixing vmin and vmax keeps 0 at the neutral centre of the diverging colormap. Set the tick labels to the column names, write each value with ax.text in a loop and add fig.colorbar(im) as a key. seaborn's sns.heatmap(corr, annot=True, cmap='coolwarm') does all of this in one call. Heatmaps also suit pivot tables such as sales by city and month.
Why we use it
With many columns, a table of correlations is hard to scan. A heatmap shows at a glance which features are strongly related to the target or to each other, which guides feature selection and warns about duplicated information.
When to use it
Use a heatmap for correlation matrices, confusion matrices and two-way pivot tables (city x month). Use a diverging colormap with fixed -1 to 1 limits for correlations; for raw counts or amounts use a sequential colormap.
How it works
- DataFrame of numeric columns
- corr = df.corr() builds the matrix
- ax.imshow(corr, cmap='RdBu_r', vmin=-1, vmax=1)
- Label ticks with column names and write values with ax.text
- Any pair near +1 or -1? Yes: Strong relationship: check for redundancy. No: Weak or no linear link.
- Correlation heatmap
Syntax
corr = df.corr(numeric_only=True)
im = ax.imshow(corr, cmap='RdBu_r', vmin=-1, vmax=1)
ax.set_xticks(range(n)); ax.set_xticklabels(corr.columns)
fig.colorbar(im, ax=ax)
# seaborn: sns.heatmap(corr, annot=True)Example
corr = df.corr(numeric_only=True)
fig, ax = plt.subplots()
im = ax.imshow(corr, cmap='RdBu_r', vmin=-1, vmax=1)
fig.colorbar(im, ax=ax)Key points
- df.corr() values run from -1 to 1; the diagonal is 1
- Use a diverging colormap with vmin=-1, vmax=1
- Annotate cells so exact values can be read
- Correlation measures straight-line relationships only
- Also great for confusion matrices and pivot tables