Heatmaps and Matrix Visualizations
What you'll learn: How to create annotated heatmaps for correlation matrices and tabular data using seaborn.heatmap.
The Power of Heatmaps for Matrix Data
A heatmap transforms a matrix of numbers into a color-coded visual where each cell's color represents its value. Think of it like a weather map showing temperature—warmer colors indicate higher values, cooler colors show lower values. This makes patterns in large tables instantly visible to the human eye.
Seaborn's heatmap() function is particularly powerful for displaying correlation matrices, confusion matrices, or any two-dimensional data where you want to see relationships at a glance.
Creating Annotated Heatmaps
The basic syntax is straightforward:
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# Create a correlation matrix
df = pd.DataFrame({
'A': [1, 2, 3, 4],
'B': [2, 4, 6, 8],
'C': [4, 3, 2, 1]
})
corr = df.corr()
# Create annotated heatmap
sns.heatmap(corr, annot=True, cmap='coolwarm', center=0)
plt.title('Correlation Matrix')
plt.show()
The annot=True parameter overlays the actual numerical values on each cell—critical for precise interpretation. The cmap controls the color palette, and center=0 ensures that zero correlations appear neutral (important for correlation matrices where both positive and negative relationships exist).
You can also format annotations with fmt='.2f' for decimal control, adjust color bar ranges with vmin and vmax, and add gridlines with linewidths=0.5.
Key Takeaway: seaborn.heatmap() with annot=True transforms matrices into intuitive color-coded visualizations where both color intensity and numerical values help identify patterns, making it essential for exploring correlation structures and tabular relationships.