Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redefine a color for a specific value in a matplotlib colormap

I want to use the colormap rainbow in an image using imshow. It works perfectly, but I want to redefine the color for the value 0. Instead of violete, I want to use white.

I want to do this only for the value zero, all other values can stay with the default values in the colormap.

Any idea how to do this without having to edit the colormap manually?

like image 571
otmezger Avatar asked May 06 '13 13:05

otmezger


People also ask

What is CMAP =' viridis?

( cmaps.viridis is a matplotlib.colors.ListedColormap ) import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import colormaps as cmaps img=mpimg.imread('stinkbug.png') lum_img = np.flipud(img[:,:,0]) imgplot = plt.pcolormesh(lum_img, cmap=cmaps.viridis)


1 Answers

You can also use set_under which I think makes more semantic sense than using set_bad

my_cmap = matplotlib.cm.get_cmap('rainbow') my_cmap.set_under('w') imshow(np.arange(25).reshape(5, 5),        interpolation='none',        cmap=my_cmap,        vmin=.001) 

You can tweak the colorbar to also show the 'under' (and the symmetric 'over') color using the kwarg extend, see example and docs.

For an answer to a duplicate with more complete examples see How to create matplotlib colormap that treats one value specially?

like image 150
tacaswell Avatar answered Oct 03 '22 05:10

tacaswell