Quantcast
Viewing all articles
Browse latest Browse all 11

Answer by Chidi for How do I make a single legend for many subplots?

If you are using subplots with bar charts, with a different colour for each bar, it may be faster to create the artefacts yourself using mpatches.

Say you have four bars with different colours as r, m, c, and k, you can set the legend as follows:

import matplotlib.patches as mpatchesimport matplotlib.pyplot as pltlabels = ['Red Bar', 'Magenta Bar', 'Cyan Bar', 'Black Bar']###################################### Insert code for the subplots here ####################################### Now, create an artist for each colorred_patch = mpatches.Patch(facecolor='r', edgecolor='#000000') # This will create a red bar with black borders, you can leave out edgecolor if you do not want the bordersblack_patch = mpatches.Patch(facecolor='k', edgecolor='#000000')magenta_patch = mpatches.Patch(facecolor='m', edgecolor='#000000')cyan_patch = mpatches.Patch(facecolor='c', edgecolor='#000000')fig.legend(handles = [red_patch, magenta_patch, cyan_patch, black_patch], labels=labels,       loc="center right",       borderaxespad=0.1)plt.subplots_adjust(right=0.85) # Adjust the subplot to the right for the legend

Viewing all articles
Browse latest Browse all 11

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>