【问题标题】:Matplotlib Legends for barh用于 barh 的 Matplotlib 图例
【发布时间】:2015-11-25 13:03:14
【问题描述】:

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

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

谢谢。

地鳄

【问题讨论】:

    标签: python matplotlib legend


    【解决方案1】:

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

    plt.legend(h, people)
    

    【讨论】:

      猜你喜欢
      • 2017-07-31
      • 2012-09-26
      • 2019-01-30
      • 2019-02-27
      • 2020-08-18
      • 2016-03-08
      • 1970-01-01
      • 2016-05-15
      • 1970-01-01
      相关资源
      最近更新 更多