Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib Legends for barh

I am a beginner with python and matplotlib. I want to create a horizontal bar chart with a legend. My code:

import matplotlib.pyplot as plt
plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

# Example data
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))
clr = ('blue', 'forestgreen', 'gold', 'red', 'purple')

h = plt.barh(y_pos, performance, xerr=error, align='center', 
alpha=0.4, label=people, color=clr)
plt.yticks(y_pos, people)
plt.xlabel('Performance')
plt.title('How fast do you want to go today?')

plt.legend(handles=[h])

plt.show()

But in the legend I have only one element. But I want a legend with one element for each person with a rectangle in the rigth color.

Thanks.

Geosucher

like image 464
Geosucher Avatar asked Nov 25 '15 13:11

Geosucher


1 Answers

Pass the handles to your bars and the legend labels separately to plt.legend:

plt.legend(h, people)

enter image description here

like image 161
xnx Avatar answered Nov 08 '22 19:11

xnx