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.
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()
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With