0

I want to graph multiple different bar charts and the colors in each graph will vary depending on the data being plotted. I would like to have a legend with handles (to accompany each set of data and provide more detailed information) to make it clear what set of data each color represents.

ex: I may have two sets of data to plot. I can hardcode that easily (with some help from the patches library):

red_patch = mpatches.Patch(color ='red', label='red data')
blue_patch = mpatches.Patch(color ='blue', label='blue data')
ax.legend(handles=[red_patch, blue_patch])

Output

But then in other cases I may want another color or even a few extra colors so the output could look like (in this case, don't need blue):

red_patch = mpatches.Patch(color ='red', label='red data')
blue_patch = mpatches.Patch(color ='blue', label='blue data')
yellow_patch = mpatches.Patch(color ='yellow', label='yellow data')
green_patch = mpatches.Patch(color ='green', label='green data')

ax.legend(handles=[red_patch, yellow_patch, green_patch])

Output2

I can define all the colors/handles but it's not really possible to hardcode every possible ax.legend call. That brings me to my question: Can I even use matplotlib handles dynamically?

ax.legend(handles=[])

I have a corresponding array that tells me which colors I want/need to show but I need a solution on how I can transfer that over for use in handles or a legend.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Eric Q
  • 29
  • 2
  • Try looking at [Dynamically add legends to matplotlib plots in python](https://stackoverflow.com/questions/16264748/dynamically-add-legends-to-matplotlib-plots-in-python?adlt=strict&toWww=1&redig=38956838EF66497584FA338EEAF10DB0). – Alias Cartellano Sep 20 '22 at 17:19
  • Insightful, but I'm plotting using matplotlib.pyplot.barh, in which I call a dataframe just once per graph to plot multiple bars. That solution will just show the first single color. – Eric Q Sep 20 '22 at 18:12

1 Answers1

0

Have you tried using f-string formating? Using a list of the plot name you just have to retrieve them and add them to the label maybe ?

Chris Ze Third
  • 632
  • 2
  • 18
  • Could you add a line of code as an example of your solution? – Javier Sep 26 '22 at 11:21
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Javier Sep 26 '22 at 11:21