Matplotlib传说为barh

时间:2015-11-25 13:03:15

标签: python matplotlib legend

我是python和matplotlib的初学者。我想创建一个带图例的水平条形图。 我的代码:

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()

但是在传说中我只有一个元素。但是我想要一个带有一个元素的图例,每个人都有一个矩形的颜色。

感谢。

Geosucher

1 个答案:

答案 0 :(得分:6)

将句柄分别传递到条形和图例标签plt.legend

plt.legend(h, people)

enter image description here

相关问题