How to Create Heatmap in Matplotlib: Simple Guide
To create a heatmap in
matplotlib, use the imshow() function with a 2D array of data. Customize the color scheme with the cmap parameter to visually represent data intensity.Syntax
The basic syntax to create a heatmap in matplotlib is:
plt.imshow(data, cmap='color_map'): Displays the 2D data as an image with colors.data: A 2D array or matrix representing values to visualize.cmap: The color map to use for coloring the heatmap (e.g., 'viridis', 'hot', 'cool').plt.colorbar(): Adds a color scale legend to interpret values.
python
import matplotlib.pyplot as plt import numpy as np data = np.array([[1, 2], [3, 4]]) plt.imshow(data, cmap='viridis') plt.colorbar() plt.show()
Example
This example shows how to create a heatmap from a 5x5 matrix with random values. It uses the 'hot' color map and includes a color bar to explain the colors.
python
import matplotlib.pyplot as plt import numpy as np # Create a 5x5 matrix with random values np.random.seed(0) data = np.random.rand(5,5) # Plot heatmap plt.imshow(data, cmap='hot') plt.colorbar() # Show color scale plt.title('Heatmap Example') plt.show()
Output
A 5x5 colored grid where colors range from dark red (low) to bright yellow (high) with a color bar on the right.
Common Pitfalls
Common mistakes when creating heatmaps include:
- Passing 1D data instead of 2D arrays, which causes errors or incorrect plots.
- Not adding
plt.colorbar(), making it hard to interpret colors. - Using inappropriate color maps that do not clearly show data differences.
- Not setting aspect ratio, which can distort the heatmap shape.
Always ensure your data is 2D and add a color bar for clarity.
python
import matplotlib.pyplot as plt import numpy as np # Wrong: 1D data # data = np.array([1, 2, 3, 4]) # Right: 2D data np.random.seed(1) data = np.random.rand(4,4) plt.imshow(data, cmap='coolwarm', aspect='auto') plt.colorbar() plt.title('Correct Heatmap') plt.show()
Output
A 4x4 heatmap with blue to red colors and a color bar, correctly showing the data matrix.
Quick Reference
Tips for creating heatmaps with matplotlib:
- Use
plt.imshow()with 2D numeric data. - Choose a suitable
cmaplike 'viridis', 'hot', or 'coolwarm'. - Add
plt.colorbar()to explain colors. - Set
aspect='auto'to avoid distortion. - Label your plot with
plt.title()and axis labels if needed.
Key Takeaways
Use plt.imshow() with a 2D array to create a heatmap in matplotlib.
Always add plt.colorbar() to help interpret the heatmap colors.
Choose an appropriate color map (cmap) to clearly show data differences.
Ensure your data is 2D; 1D data will not display correctly as a heatmap.
Set aspect='auto' to keep the heatmap shape proportional.