相关矩阵热力图
使用 DataFrame.corr() 计算相关矩阵,并使用 sns.heatmap 将其可视化为按颜色编码的热力图。
相关矩阵热力图 是 CoddyKit 上的免费 Pandas & NumPy Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Pandas & NumPy Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Pandas & NumPy Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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.
常见问题解答
「相关矩阵热力图」课时是免费的吗?
是的 — 「相关矩阵热力图」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Pandas & NumPy Academy 课程的其余内容,请升级到 CoddyKit PRO。 Pandas & NumPy Academy 课程共包含 4 节课。
「相关矩阵热力图」这节课中我会学到什么?
使用 DataFrame.corr() 计算相关矩阵,并使用 sns.heatmap 将其可视化为按颜色编码的热力图。 你通过在浏览器中直接运行的动手代码来练习 Pandas & NumPy Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Pandas & NumPy Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Pandas & NumPy Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「相关矩阵热力图」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Pandas & NumPy Academy 课中编写并运行代码吗?
能。每节 Pandas & NumPy Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。