0
0
MatplotlibHow-ToBeginner ยท 3 min read

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 cmap argument, 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 NameDescription
viridisDefault perceptually uniform colormap from purple to yellow
plasmaBright colormap from dark purple to yellow
infernoDark to bright colormap with warm colors
magmaDark to bright colormap with purple and orange tones
cividisColorblind-friendly blue to yellow colormap
grayGrayscale colormap
jetRainbow 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.