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

标签 python matplotlib histogram

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

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

产生这个:

enter image description here

如何在其中获取三种不同颜色的图例?

最佳答案

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

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

完整示例:

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

关于python - 具有多个图例条目的 Matplotlib 直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43872450/

相关文章:

python - Scrapy-Splash:无法使用 scrapinghub/splash:latest 作为基础镜像运行 docker 容器

python - Pandas 计算多列数据中列减去的平均值

python - 比较两组之间的每个元素?

R 软件直方图,包含所有打印的 x 值

android - Renderscript 中的直方图匹配

matlab - 带有 gnuplot 或 octave 的 3D 直方图

python - Plotly:在 jupyter 笔记本中以编程方式平移 3D 图形

python - 在 Cloud 9 Ide 上使用 matplotlib

python - matplotlib 条形图 : space out bars

python - 从 matplotlib 图获取最高 zorder 对象