Matplotlib Legends for barh
Question: 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


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

    
    
    plt.legend(h, people)
    

[![enter image description
here](http://i.stack.imgur.com/Ki9lZ.png)](http://i.stack.imgur.com/Ki9lZ.png)

