1

I'm trying to plot a bar graph in which certain bars need to be highlighted. How do I include a legend that explains what the colored bars are?

Below is my code. I want the legend to indicate that "Relevant bars" are blue (not gray, as it says at the moment).

import matplotlib.pyplot as plt

data = range(1,6)
labels = ['a','b','c','d','e']
relevant_bars = ['b','e']

bars = plt.bar(data, data, color='gray')

for i in range(len(bars)):
    if labels[i] in relevant_bars:
        bars[i].set_color('blue')

plt.xticks(pos, labels)
plt.legend(['Relevant bars']);

enter image description here

  • See also [Custom legend in Pandas bar plot](https://stackoverflow.com/questions/29639973/custom-legend-in-pandas-bar-plot-matplotlib) – JohanC Dec 27 '20 at 20:22

2 Answers2

2

change

   plt.legend(['Relevant bars']);

to

    legend_elements = [Line2D([0], [0], color='b', lw=4, label='Relevant bars')]
    plt.legend(handles=legend_elements);
0

Just take the rectangle patch of the legend and set its color:

legend = plt.legend(['Relevant bars'])
legend.get_patches()[0].set_color('b')
Stef
  • 28,728
  • 2
  • 24
  • 52