How to redefine a color for a specific value in a Matplotlib colormap?

In Matplotlib, you can customize colormaps by redefining colors for specific value ranges. This is useful when you want to highlight out-of-range values or create custom color schemes for data visualization.

Basic Colormap Customization

Use set_under() to define colors for values below the colormap range ?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm

# Get a colormap instance
cmap = cm.get_cmap('gray')

# Set color for out-of-range low values
cmap.set_under('red')

# Create sample data
data = np.arange(25).reshape(5, 5)

# Display with custom colormap
plt.imshow(data, interpolation='none', cmap=cmap, vmin=5)
plt.colorbar()
plt.title('Values below vmin=5 shown in red')
plt.show()

Setting Colors for High and Low Values

You can customize both ends of the colormap using set_under() and set_over() ?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm

# Create colormap with custom out-of-range colors
cmap = cm.get_cmap('viridis')
cmap.set_under('blue')    # Values below vmin
cmap.set_over('red')      # Values above vmax

# Create sample data with wider range
data = np.random.rand(10, 10) * 100

plt.figure(figsize=(8, 6))
plt.imshow(data, cmap=cmap, vmin=20, vmax=80)
plt.colorbar(extend='both')  # Show extended colors
plt.title('Custom colors for out-of-range values')
plt.show()

Creating Custom Colormaps

For more control, create a custom colormap with specific colors ?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

# Create custom colormap
colors = ['purple', 'blue', 'green', 'yellow', 'orange', 'red']
custom_cmap = ListedColormap(colors)

# Set special colors for out-of-range values
custom_cmap.set_under('black')
custom_cmap.set_over('white')

# Sample data
data = np.random.randint(0, 10, (8, 8))

plt.figure(figsize=(8, 6))
plt.imshow(data, cmap=custom_cmap, vmin=2, vmax=8)
plt.colorbar(extend='both')
plt.title('Custom colormap with special boundary colors')
plt.show()

Key Methods

Method Purpose Usage
set_under() Color for values below vmin cmap.set_under('red')
set_over() Color for values above vmax cmap.set_over('blue')
extend='both' Show extended colors in colorbar plt.colorbar(extend='both')

Conclusion

Use set_under() and set_over() to customize colormap boundaries. The extend parameter in colorbar() displays these custom colors, making out-of-range values clearly visible in your plots.

Updated on: 2026-03-25T19:54:00+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements