Plotting Legend For 2d Numpy Array
I like to create a legend based on certain numbers using Numpy and Matplotlib but to no avail. So I started to play around with a test function to get it right before transferring
Solution 1:
Proxy artists
This can be done via proxy artists. Example from the docs:
import matplotlib.patchesas mpatches
import matplotlib.pyplotas plt
red_patch = mpatches.Patch(color='red', label='The red data')
plt.legend(handles=[red_patch])
plt.show()
But you need to figure out which colours correspond to which values. E.g.
cmap = plt.cm.viridismy_colors= {
'Mineral 1' : 0.1,
'Mineral 2' : 0.2,
}
patches = [mpatches.Patch(color=cmap(v), label=k) for k,v in my_colors.items()]
plt.legend(handles=patches)
The numbers in the dictionary correspond to the data normalized to [0,1] and you need to plot your data with the same cmap
, of course.
Alternative: Colorbar
Alternatively, you can add a colorbar
(the equivalent to the legend in imshow
plots and the like) and place your labels on the ticks.
cbar = plt.colorbar(cax, ticks=list(my_colors.values()), orientation='horizontal')
cbar.ax.set_xticklabels(list(my_colors.keys()))
Post a Comment for "Plotting Legend For 2d Numpy Array"