Heatmaps: Visualizing Matrices and Correlations
You'll learn how to create heatmaps that use color to reveal patterns in 2D data and correlation matrices.
What Is a Heatmap?
A heatmap is a data visualization where values in a matrix are represented as colors. Think of it like a weather map showing temperature zones—hotter colors indicate higher values, cooler colors show lower values. This makes spotting patterns in large datasets immediate and intuitive.
In data science, heatmaps excel at two tasks: visualizing correlation matrices (which variables move together?) and displaying any 2D data where you want to compare values across two categorical dimensions.
Creating Heatmaps in Matplotlib
Matplotlib's imshow() or pcolor() functions display 2D arrays as colored grids:
import matplotlib.pyplot as plt
import numpy as np
# Create a correlation matrix
data = np.random.rand(5, 5)
plt.imshow(data, cmap='coolwarm')
plt.colorbar(label='Correlation')
plt.title('Correlation Heatmap')
plt.xticks(range(5), ['Var1', 'Var2', 'Var3', 'Var4', 'Var5'])
plt.yticks(range(5), ['Var1', 'Var2', 'Var3', 'Var4', 'Var5'])
plt.show()
Adding Annotations for Clarity
Numbers overlaid on cells help readers see exact values:
fig, ax = plt.subplots()
im = ax.imshow(data, cmap='coolwarm')
# Add text annotations
for i in range(5):
for j in range(5):
text = ax.text(j, i, f'{data[i, j]:.2f}',
ha="center", va="center", color="black")
plt.colorbar(im)
plt.show()
The color encoding provides the "big picture" while annotations give precision.
Key Takeaway: Heatmaps transform numerical matrices into color-coded grids, making correlation patterns and 2D data comparisons visually obvious—add annotations when exact values matter.