Set a colormap of an image in Matplotlib

A colormap in Matplotlib defines how numerical data values are mapped to colors when displaying images. You can apply different colormaps to visualize image data in various color schemes.

Basic Colormap Usage

Here's how to apply a colormap to an image using matplotlib ?

import matplotlib.pyplot as plt
import numpy as np

# Create sample image data
data = np.random.random((100, 100))

plt.figure(figsize=(8, 6))
plt.imshow(data, cmap='hot')
plt.colorbar()
plt.title('Hot Colormap')
plt.axis('off')
plt.show()

Working with Real Image Data

When working with RGB images, you typically need to extract a single channel before applying a colormap ?

import matplotlib.pyplot as plt
import matplotlib.image as mimg

# Set figure parameters
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Read image and extract one channel
img = mimg.imread('bird.jpg')
lum_img = img[:, :, 0]  # Extract red channel

# Apply colormap
plt.imshow(lum_img, cmap="hot")
plt.axis('off')
plt.show()

Popular Colormaps

Here are some commonly used colormaps you can apply ?

import matplotlib.pyplot as plt
import numpy as np

# Create sample data
data = np.random.random((50, 50))

# Create subplots for different colormaps
fig, axes = plt.subplots(2, 2, figsize=(10, 8))

colormaps = ['viridis', 'plasma', 'hot', 'cool']
titles = ['Viridis', 'Plasma', 'Hot', 'Cool']

for i, (cmap, title) in enumerate(zip(colormaps, titles)):
    ax = axes[i // 2, i % 2]
    im = ax.imshow(data, cmap=cmap)
    ax.set_title(title)
    ax.axis('off')
    plt.colorbar(im, ax=ax)

plt.tight_layout()
plt.show()

Colormap Categories

Category Examples Best For
Sequential viridis, plasma, hot Ordered data
Diverging coolwarm, seismic Data with meaningful center
Qualitative tab10, Set1 Categorical data

Custom Colormap Range

You can also control the value range for colormap mapping ?

import matplotlib.pyplot as plt
import numpy as np

data = np.random.random((100, 100)) * 10

plt.figure(figsize=(12, 4))

# Default range
plt.subplot(1, 3, 1)
plt.imshow(data, cmap='viridis')
plt.title('Default Range')
plt.colorbar()

# Custom vmin, vmax
plt.subplot(1, 3, 2)
plt.imshow(data, cmap='viridis', vmin=2, vmax=8)
plt.title('Limited Range (2-8)')
plt.colorbar()

# Centered colormap
plt.subplot(1, 3, 3)
plt.imshow(data - 5, cmap='coolwarm', vmin=-5, vmax=5)
plt.title('Centered at 0')
plt.colorbar()

plt.tight_layout()
plt.show()

Conclusion

Use cmap parameter in imshow() to apply colormaps to images. Choose sequential colormaps for ordered data, diverging for centered data, and control the range with vmin and vmax parameters.

Updated on: 2026-03-25T22:13:13+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements