How to Use Colormap in Matplotlib for Color Mapping
In
matplotlib, you use colormaps by passing a cmap argument to plotting functions like imshow, scatter, or contourf. Colormaps map numeric data to colors, making it easier to visualize data ranges and patterns.Syntax
The basic syntax to use a colormap in matplotlib is by adding the cmap parameter to your plotting function. For example, plt.imshow(data, cmap='viridis') applies the 'viridis' colormap to the image.
Here is what each part means:
plt.imshow: Function to display image data.data: Your numeric data array.cmap: The colormap name or object to map data values to colors.
python
plt.imshow(data, cmap='viridis')Example
This example shows how to use the viridis colormap with imshow to display a 2D array with colors representing values.
python
import matplotlib.pyplot as plt import numpy as np # Create sample 2D data np.random.seed(0) data = np.random.rand(10, 10) # Plot data with colormap plt.imshow(data, cmap='viridis') plt.colorbar() # Show color scale plt.title('Example of colormap usage') plt.show()
Output
A 10x10 colored grid image with a colorbar showing the 'viridis' gradient from dark purple to yellow.
Common Pitfalls
Common mistakes when using colormaps include:
- Not passing the
cmapargument, so the default colormap is used. - Using a colormap name that does not exist, causing an error.
- Applying colormaps to data types that don't support it, like categorical data without numeric mapping.
- Forgetting to add a colorbar, which helps interpret the colors.
Example of wrong and right usage:
python
# Wrong: misspelled colormap name plt.imshow(data, cmap='viridiss') # This will raise an error # Right: correct colormap name plt.imshow(data, cmap='viridis')
Quick Reference
| Colormap Name | Description |
|---|---|
| viridis | Default perceptually uniform colormap from purple to yellow |
| plasma | Bright colormap from dark purple to yellow |
| inferno | Dark to bright colormap with warm colors |
| magma | Dark to bright colormap with purple and orange tones |
| cividis | Colorblind-friendly blue to yellow colormap |
| gray | Grayscale colormap |
| jet | Rainbow colormap (not recommended for accuracy) |
Key Takeaways
Use the cmap parameter in matplotlib plotting functions to apply colormaps.
Choose colormaps that suit your data and audience, preferring perceptually uniform ones like 'viridis'.
Always add a colorbar to help interpret the color scale.
Check colormap names carefully to avoid errors.
Colormaps work best with numeric data representing ranges or intensities.