Matplot imshow add label to each color and put in legend

I want to show an image as below (copied from here ) in matplotlib

enter image description here

But I want to mark each color and put it in the legend on the side, is there a way to do this please?

+1


source to share


1 answer


I suppose that it makes sense to put a legend for all values ​​in the matrix if there are not so many of them. So let's say you have 8 different values ​​in your matrix. Then we can create a proxy artist of the corresponding color for each one and put them in a legend like this

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

# create some data
data = np.random.randint(0, 8, (5,5))
# get the unique values from data
# i.e. a sorted list of all values in data
values = np.unique(data.ravel())

plt.figure(figsize=(8,4))
im = plt.imshow(data, interpolation='none')

# get the colors of the values, according to the 
# colormap used by imshow
colors = [ im.cmap(im.norm(value)) for value in values]
# create a patch (proxy artist) for every color 
patches = [ mpatches.Patch(color=colors[i], label="Level {l}".format(l=values[i]) ) for i in range(len(values)) ]
# put those patched as legend-handles into the legend
plt.legend(handles=patches, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0. )

plt.grid(True)
plt.show()

      



enter image description here

+4


source







All Articles