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
Pass the handles to your bars and the legend labels separately to plt.legend
:
plt.legend(h, people)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With