简体   繁体   English

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

[英]Matplotlib histogram with multiple legend entries

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: 产生这个:

在此输入图像描述

How do I get a legend in there for the three different colors? 如何在这里获得三种不同颜色的图例?

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

在此输入图像描述

According to me you just need to pass the required label as an argument in the hist function, eg 根据我的说法,你只需要在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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM