I need to create a linear color map with a color for "errors"

Question:

I need to create a color map that behaves linearly between 0 and 1 on a grey scale.
Then I also want that any number outside the range [0,1] is drown red.

Would it be possible?

Asked By: Aslan986

||

Answers:

You can take one of the existing black-white colormaps, and set its extremes to red. under and over set the color for values under or over the normalized bounds. bad is for color values that are NaN or infinity.

A copy() is needed to prevent changing matplotlib’s own copy of the colormap. When applying the colormap, it should go together with either explicitly setting vmin=0 and vmax=1, or using a norm.

To show the extremes in a colorbar, the extend= parameter can be used.

Here is an example, using the y-value for coloring.

import matplotlib.pyplot as plt
import numpy as np

my_cmap = plt.get_cmap('binary_r').copy()
my_cmap.set_extremes(bad='r', under='r', over='r')
np.random.seed(112358)
y = np.random.randn(200).cumsum() / 10
plt.scatter(x=np.arange(200), y=y, c=y, cmap=my_cmap, vmin=0, vmax=1)
plt.colorbar(extend='both')
plt.tight_layout()
plt.show()

colormap with red extremes

Answered By: JohanC
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.