How to create a matplotlib colormap that treats one value specially?


To create a matplotlib colormap that treats one value specially, we can take the following steps −

  • Set the figure size and adjust the padding between and around the subplots.
  • Get a colormap instance, name is "rainbow".
  • Set the color for low out-of-range values, using set_under('red') method.
  • Create random data and eps using numpy.
  • Create a figure and a set of subplots.
  • Display data as an image, i.e., on a 2D regular raster, using imshow() method.
  • Create a colorbar for a ScalarMappable instance, im.
  • To display the figure, use show() method.

Example

import matplotlib.pyplot as plt
import numpy as np

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

cmap = plt.get_cmap('rainbow')
cmap.set_under('red')

data = np.random.randn(5, 5)
eps = np.spacing(0.0)

fig, ax = plt.subplots()
im = ax.imshow(data, interpolation='nearest', vmin=eps, cmap=cmap)
fig.colorbar(im, extend='min')

plt.show()

Output

Updated on: 03-Aug-2021

451 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements