gpt4 book ai didi

python - Barh 的 Matplotlib 传奇

转载 作者:太空狗 更新时间:2023-10-30 01:00:38 26 4
gpt4 key购买 nike

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

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

谢谢。

地质勘探者

最佳答案

将句柄传递给您的条形图,将图例标签分别传递给 plt.legend:

plt.legend(h, people)

enter image description here

关于python - Barh 的 Matplotlib 传奇,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33917230/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com