python imshow, set certain value to defined color

I will answer the general question of how to set a particular value to a particular color regardless of the color map.

In the code below for illustration purposes I supposed that is the value -1 that you want to map white. You will be wanting to do something different for your code.

This technique uses a masked array to set the parts where your data is equal to -1 (the value you wish to map) and then uses cmap.set_bad() to assign the color white to this value.

import numpy as np
import matplotlib
import matplotlib.pyplot as plt

value = -1
data = np.arange(100).reshape((10, 10))
data[5, :] = -1  # Values to set -1

masked_array = np.ma.masked_where(data == value, data)

cmap = matplotlib.cm.spring  # Can be any colormap that you want after the cm
cmap.set_bad(color="white")

plt.imshow(masked_array, cmap=cmap)
plt.show()

enter image description here

Hope it helps.

Leave a Comment