Heatmaps for Correlation Matrices
Compute a correlation matrix with DataFrame.corr() and visualise it as a colour-coded heatmap with sns.heatmap.
Heatmaps for Correlation Matrices is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is a Correlation Matrix?
A correlation matrix is a square table where entry (i, j) contains the Pearson correlation coefficient between column i and column j. Values range from -1 (perfect negative linear correlation) to +1 (perfect positive), with 0 meaning no linear relationship. The diagonal is always 1 (a variable is perfectly correlated with itself). Correlation matrices are the first step in understanding which variables move together before building a model.
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Compute correlation matrix for numeric columns
tips = sns.load_dataset('tips')
corr = tips[['total_bill', 'tip', 'size']].corr()
print(corr.round(2))Computing the Correlation Matrix
Call DataFrame.corr() to compute pairwise Pearson correlations for all numeric columns. The method parameter controls which correlation to compute: 'pearson' (default, linear), 'spearman' (rank-based, robust to outliers and non-linear monotonic relationships), or 'kendall'. For skewed financial or count data, Spearman is often more informative than Pearson.
import pandas as pd
import seaborn as sns
tips = sns.load_dataset('tips')
numeric = tips.select_dtypes(include='number')
# Pearson vs Spearman
pearson = numeric.corr(method='pearson')
spearman = numeric.corr(method='spearman')
print('Pearson:')
print(pearson.round(2))
print('\nSpearman:')
print(spearman.round(2))Basic Heatmap with sns.heatmap
sns.heatmap(data) takes a 2D array or DataFrame and renders it as a colour grid — each cell's colour encodes its numeric value. When applied to a correlation matrix, warm colours (red) typically represent positive correlation and cool colours (blue) represent negative. The annot=True parameter prints the numeric value inside each cell, which is essential for reading a correlation heatmap accurately.
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
corr = tips.select_dtypes('number').corr()
sns.heatmap(corr, annot=True, fmt='.2f')
plt.title('Correlation Heatmap — Tips Dataset')
plt.tight_layout()
plt.show()Choosing the Right Colour Map
For correlation matrices, always use a diverging colour map centred at zero: cmap='coolwarm', 'RdBu_r', or 'vlag'. These maps use one colour for positive values, another for negative, and a neutral midpoint at zero. Avoid sequential colour maps (like 'Blues') for correlation data because they make it impossible to distinguish positive from negative correlations visually. Set vmin=-1, vmax=1 to fix the colour scale to the full correlation range.
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
corr = tips.select_dtypes('number').corr()
sns.heatmap(
corr,
annot=True,
fmt='.2f',
cmap='coolwarm',
vmin=-1,
vmax=1,
center=0
)
plt.title('Correlation Heatmap with Diverging Palette')
plt.tight_layout()
plt.show()Masking the Upper Triangle
Because a correlation matrix is symmetric (corr[i,j] == corr[j,i]), showing both halves is redundant. Use np.triu to create an upper-triangle mask and pass it to mask= in sns.heatmap. This cuts the number of cells in half, making the plot less cluttered and easier to read. The diagonal values (all 1.0) can also be masked since they carry no information.
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
tips = sns.load_dataset('tips')
corr = tips.select_dtypes('number').corr()
# Mask the upper triangle (including diagonal)
mask = np.triu(np.ones_like(corr, dtype=bool))
sns.heatmap(
corr,
mask=mask,
annot=True,
fmt='.2f',
cmap='coolwarm',
vmin=-1,
vmax=1
)
plt.title('Lower-Triangle Correlation Heatmap')
plt.tight_layout()
plt.show()Customising Annotation and Cell Size
Control the annotation format with fmt= (e.g. '.2f' for two decimal places) and the font size with annot_kws={'size': 10}. The linewidths parameter adds thin lines between cells, making the grid easier to read for large matrices. Use square=True to force square cells regardless of the figure dimensions, which gives heatmaps a clean, balanced appearance.
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# Load a wider dataset for a more interesting heatmap
penguins = sns.load_dataset('penguins').select_dtypes('number')
corr = penguins.corr()
mask = np.triu(np.ones_like(corr, dtype=bool))
sns.heatmap(
corr,
mask=mask,
annot=True,
fmt='.2f',
cmap='vlag',
vmin=-1,
vmax=1,
linewidths=0.5,
square=True,
annot_kws={'size': 10}
)
plt.title('Penguins Correlation Matrix')
plt.tight_layout()
plt.show()Clustering with clustermap
sns.clustermap() reorders rows and columns using hierarchical clustering to group variables with similar correlation patterns together. This makes it much easier to identify blocks of correlated features in large matrices. The dendrogram on the top and left axes shows the clustering tree. Use method='ward' and metric='euclidean' as sensible defaults for correlation-based clustering.
import seaborn as sns
import matplotlib.pyplot as plt
penguins = sns.load_dataset('penguins').select_dtypes('number').dropna()
corr = penguins.corr()
sns.clustermap(
corr,
cmap='coolwarm',
vmin=-1,
vmax=1,
annot=True,
fmt='.2f',
figsize=(6, 6)
)
plt.suptitle('Clustered Correlation Matrix', y=1.02)
plt.show()Heatmap for Pivot Table Data
Heatmaps are not limited to correlation matrices — any 2D numeric table benefits from colour encoding. A common pattern is to compute a pivot table (e.g. average tip by day and time) and then visualise it as a heatmap. This turns a dense table of numbers into an instantly scannable colour grid where the highest and lowest values jump out visually.
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
tips = sns.load_dataset('tips')
# Pivot: average bill by day and time
pivot = tips.pivot_table(
values='total_bill',
index='day',
columns='time',
aggfunc='mean'
)
sns.heatmap(pivot, annot=True, fmt='.1f', cmap='YlOrRd')
plt.title('Average Bill by Day and Time')
plt.tight_layout()
plt.show()Interpreting Correlation Values
When interpreting correlations, use these rough benchmarks: |r| < 0.2 = negligible, 0.2-0.4 = weak, 0.4-0.6 = moderate, 0.6-0.8 = strong, > 0.8 = very strong. However, correlation tells you nothing about causation, and can be spurious (coincidentally correlated due to a third confounding variable). Always pair numerical correlation analysis with scatter plots to verify the relationship is actually linear and not driven by outliers.
import pandas as pd
import seaborn as sns
# Find the most correlated pairs
penguins = sns.load_dataset('penguins').select_dtypes('number').dropna()
corr = penguins.corr()
# Unstack to get pairs, remove self-correlations, sort
pairs = (corr
.unstack()
.reset_index()
.rename(columns={'level_0': 'var1', 'level_1': 'var2', 0: 'r'})
.query('var1 != var2')
.assign(abs_r=lambda df: df['r'].abs())
.sort_values('abs_r', ascending=False)
.drop_duplicates(subset='abs_r')
)
print(pairs.head(6).to_string(index=False))Large Dataset Heatmaps: Subsetting
For DataFrames with many columns, a full correlation heatmap becomes unreadable. A better approach is to filter the correlation matrix to show only pairs with |r| above a threshold (e.g. 0.5), or to select only the most-correlated features with a target variable. You can also subset by domain — for example, plotting correlations among financial metrics separately from operational metrics in a business dataset.
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# Show only features with |r| > 0.4 with any other feature
penguins = sns.load_dataset('penguins').select_dtypes('number').dropna()
corr = penguins.corr()
# Filter columns that have at least one high correlation (excluding diagonal)
high_corr = (corr.abs() > 0.4).any(axis=1)
filtered = corr.loc[high_corr, high_corr]
mask = np.triu(np.ones_like(filtered, dtype=bool))
sns.heatmap(filtered, mask=mask, annot=True,
fmt='.2f', cmap='coolwarm', vmin=-1, vmax=1)
plt.title('High-Correlation Subset')
plt.tight_layout()
plt.show()Saving Heatmaps to Files
Heatmaps are often included in reports and presentations. Call plt.savefig('filename.png', dpi=150, bbox_inches='tight') after creating the heatmap to save it. The bbox_inches='tight' argument prevents axis labels from being clipped. For PDF reports, use format='pdf'. When using sns.clustermap, the figure is stored in the returned object: g = sns.clustermap(...); g.savefig('plot.png').
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
tips = sns.load_dataset('tips')
corr = tips.select_dtypes('number').corr()
mask = np.triu(np.ones_like(corr, dtype=bool))
fig, ax = plt.subplots(figsize=(6, 5))
sns.heatmap(corr, mask=mask, annot=True, fmt='.2f',
cmap='coolwarm', vmin=-1, vmax=1,
linewidths=0.5, ax=ax)
ax.set_title('Correlation Heatmap')
# Save to file
plt.savefig('/tmp/correlation_heatmap.png', dpi=150, bbox_inches='tight')
plt.close()
print('Saved to /tmp/correlation_heatmap.png')Quick Check
Test your understanding of correlation heatmaps from this lesson.
Lesson Recap
In this lesson you learned: DataFrame.corr() computes pairwise correlations, sns.heatmap renders them as a colour grid with diverging colour maps and annotation, and masking the upper triangle removes redundancy. Next up we explore the full Exploratory Data Analysis pipeline — a systematic checklist for profiling any new dataset.
Frequently asked questions
Is the “Heatmaps for Correlation Matrices” lesson free?
Yes — the full text of “Heatmaps for Correlation Matrices” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.
What will I learn in “Heatmaps for Correlation Matrices”?
Compute a correlation matrix with DataFrame.corr() and visualise it as a colour-coded heatmap with sns.heatmap. You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Pandas & NumPy Academy?
No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Heatmaps for Correlation Matrices” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Pandas & NumPy Academy lesson?
Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Distribution Plots: histplot and kdeplot
- Categorical Plots: boxplot, barplot, violinplot
- Scatter Plots and Pair Plots
- Heatmaps for Correlation Matrices