0
0
Matplotlibdata~5 mins

Image colormaps in Matplotlib

Choose your learning style9 modes available
Introduction

Colormaps help us show images with colors that make patterns easy to see. They change how numbers in images look by using colors.

When you want to show a heatmap of temperatures in a city.
When you need to display grayscale images with colors to highlight details.
When visualizing data like elevation or intensity in a picture.
When you want to make scientific images easier to understand by using colors.
When comparing different images with consistent color schemes.
Syntax
Matplotlib
import matplotlib.pyplot as plt
plt.imshow(image_data, cmap='colormap_name')
plt.colorbar()
plt.show()

image_data is your image or 2D data array.

cmap sets the colormap by name, like 'gray', 'viridis', or 'hot'.

Examples
Shows the image in grayscale colors from black to white.
Matplotlib
plt.imshow(image_data, cmap='gray')
plt.colorbar()
plt.show()
Uses the 'viridis' colormap with blue to yellow colors, good for colorblind-friendly visuals.
Matplotlib
plt.imshow(image_data, cmap='viridis')
plt.colorbar()
plt.show()
Displays the image with colors from black to red to yellow, like heat intensity.
Matplotlib
plt.imshow(image_data, cmap='hot')
plt.colorbar()
plt.show()
Sample Program

This code creates a simple 10x10 gradient image and shows it using the 'viridis' colormap. The colorbar shows how colors map to values.

Matplotlib
import numpy as np
import matplotlib.pyplot as plt

# Create a 2D array with a gradient
image_data = np.linspace(0, 1, 100).reshape(10, 10)

# Show image with 'viridis' colormap
plt.imshow(image_data, cmap='viridis')
plt.colorbar()
plt.title('Image with Viridis Colormap')
plt.show()
OutputSuccess
Important Notes

Colormaps can be sequential, diverging, or qualitative depending on your data.

Use plt.colorbar() to add a color scale next to your image.

Try different colormaps to find the best one for your data story.

Summary

Colormaps change how image data values show as colors.

Use cmap in plt.imshow() to pick a colormap.

Adding a colorbar helps explain the color meaning.