Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create matplotlib colormap that treats one value specially? [duplicate]

How can I create a matplotlib colormap that maps 0 (and only 0) to white, and any other value 0 < v <= 1 to a smooth gradient such as rainbow?

It seems neither LinearSegmentedColormap nor ListedColormap can do this.

like image 255
Szabolcs Avatar asked Aug 21 '14 17:08

Szabolcs


1 Answers

There are a few ways of doing it. From your description of your values range, you just want to use cmap.set_under('white') and then set the vmin to 0 + eps.

For example:

import matplotlib.pyplot as plt
import numpy as np

cmap = plt.get_cmap('rainbow')
cmap.set_under('white')  # Color for values less than vmin

data = np.random.random((10, 10))
data[3:5, 7:] = 0

# Very small float such that 0.0 != 0 + eps
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()

enter image description here

However, if 0 was in the middle of your data range, you could mask the values and set the color with cmap.set_bad (I'll use black as the color to distinguish from the default for masked portions.):

import matplotlib.pyplot as plt
import numpy as np

cmap = plt.get_cmap('rainbow')
cmap.set_bad('black')

data = np.random.normal(0, 1, (10, 10))
data[3:5, 7:] = 0

data = np.ma.masked_equal(data, 0)

fig, ax = plt.subplots()
im = ax.imshow(data, interpolation='nearest', cmap=cmap)
fig.colorbar(im)
plt.show()

enter image description here

like image 83
Joe Kington Avatar answered Oct 26 '22 15:10

Joe Kington