I have multiple images (numpy arrays) whose data values correspond to N different classes. Each image does not necessarily contain examples of each class. For example, there might be a total of 12 different classes (0:11), however, one image might only contain classes 1:9.
I would like to plot each image such that the color assigned to each class is the same across all images.
I've looked into several answers: here the accepted and popular answers didn't work across multiple images. here seems like it could work but I would really like to use a color map (from matplotlib import cm
) so as not to manually set colors. I would also like a means to create an appropriate colorbar containing all classes.
The code I've tried is below:
import numpy as np
from matplotlib import cm
import matplotlib.pyplot as plt
t1 = np.arange(9).reshape(3,3)
t2 = t1.copy()
t2[1,1] = 10
t3 = t2.copy()
t3[1,1] = 11
cmap = cm.get_cmap('tab20', 11)
fig, axs = plt.subplots(1,3)
axs[0].imshow(t1, cmap = cmap, vmin = 0, vmax = 11)
axs[1].imshow(t2, cmap = cmap, vmin = 0, vmax = 11)
axs[2].imshow(t3, cmap = cmap, vmin = 0, vmax = 11)