Python 具有多个图例条目的 Matplotlib 直方图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43872450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:28:19  来源:igfitidea点击:

Matplotlib histogram with multiple legend entries

pythonmatplotlibhistogram

提问by warrenfitzhenry

I have this code that produces a histogram, identifying three types of fields; "Low", "medium" , and "high":

我有这段代码可以生成直方图,识别三种类型的字段;“低”、“中”和“高”:

import pylab as plt
import pandas as pd


df = pd.read_csv('April2017NEW.csv', index_col =1)
df1 = df.loc['Output Energy, (Wh/h)']  # choose index value and Average
df1['Average'] = df1.mean(axis=1)

N, bins, patches = plt.hist(df1['Average'], 30)

cmap = plt.get_cmap('jet')
low = cmap(0.5)
medium =cmap(0.25)
high = cmap(0.8)


for i in range(0,4):
    patches[i].set_facecolor(low)
for i in range(4,11):
    patches[i].set_facecolor(medium)
for i in range(11,30):
    patches[i].set_facecolor(high)

plt.xlabel("Watt Hours", fontsize=16)  
plt.ylabel("Households", fontsize=16)
plt.xticks(fontsize=14)  
plt.yticks(fontsize=14)
ax = plt.subplot(111)  
ax.spines["top"].set_visible(False)  
ax.spines["right"].set_visible(False)

plt.show()

that produces this:

产生这个:

enter image description here

在此处输入图片说明

How do I get a legend in there for the three different colors?

我如何获得三种不同颜色的图例?

回答by ImportanceOfBeingErnest

You would need to create the legend yourself. To this end, create some rectangles, which are not shown in the figure (so called proxy artists).

您需要自己创建图例。为此,创建一些图中未显示的矩形(所谓的代理艺术家)。

#create legend
handles = [Rectangle((0,0),1,1,color=c,ec="k") for c in [low,medium, high]]
labels= ["low","medium", "high"]
plt.legend(handles, labels)

Complete example:

完整示例:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Rectangle

data = np.random.rayleigh(size=1000)*35

N, bins, patches = plt.hist(data, 30, ec="k")

cmap = plt.get_cmap('jet')
low = cmap(0.5)
medium =cmap(0.25)
high = cmap(0.8)


for i in range(0,4):
    patches[i].set_facecolor(low)
for i in range(4,11):
    patches[i].set_facecolor(medium)
for i in range(11,30):
    patches[i].set_facecolor(high)

#create legend
handles = [Rectangle((0,0),1,1,color=c,ec="k") for c in [low,medium, high]]
labels= ["low","medium", "high"]
plt.legend(handles, labels)

plt.xlabel("Watt Hours", fontsize=16)  
plt.ylabel("Households", fontsize=16)
plt.xticks(fontsize=14)  
plt.yticks(fontsize=14)

plt.gca().spines["top"].set_visible(False)  
plt.gca().spines["right"].set_visible(False)

plt.show()

enter image description here

在此处输入图片说明

回答by tsando

According to me you just need to pass the required label as an argument in the histfunction, e.g.

根据我的说法,您只需要将所需的标签作为函数中的参数传递hist,例如

plt.hist(x, bins=20, alpha=0.5, label='my label')

See example also here https://matplotlib.org/examples/statistics/histogram_demo_multihist.html

另请参见此处的示例https://matplotlib.org/examples/statistics/histogram_demo_multihist.html