-1

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.

2

1 Answer 1

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 ?

2
  • Could you add a line of code as an example of your solution?
    – Javier
    Commented Sep 26, 2022 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.
    – Javier
    Commented Sep 26, 2022 at 11:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.