Matplotlib does not support any simple way to define an explicit color map of the form:
my_map = {
1: "green",
2: "orange",
3: "red"
}
I would have to use a custom colormap with normalization that just so happens to fall onto number 1, 2, 3 (which seems like way too complicated for something so simple...), right?
The only really simple approach I found was to use cmap = ListedColormap(['green', 'orange', 'red'], 'indexed')
, which, however, will obviously break if not all numbers occur at least once, e.g. assuming the categorical data I want to plot comes as data = [2,2,2,2,2]
, but all will be mapped to green instead of orange.
CodePudding user response:
As you say, this works:
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
import numpy as np
cmap = ListedColormap(['green', 'orange', 'red'], 'indexed')
data = np.random.randint(1, 4, size=(5, 5))
plt.imshow(data, cmap=cmap)
plt.colorbar()
And produces:
But if you only have ones (say), the colourmap scales automatically. You could fix it with vmin
and vmax
:
data = np.ones((5, 5))
plt.imshow(data, cmap=cmap, vmin=1, vmax=3)
plt.colorbar()
It gives you:
Which I think is the required output.