Matplotlib/seaborn 直方图使用不同颜色的分组箱 [英] Matplotlib/seaborn histogram using different colors for grouped bins

查看:39
本文介绍了Matplotlib/seaborn 直方图使用不同颜色的分组箱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码,使用熊猫 df:

将pandas导入为pd导入matplotlib.pyplot作为plt将 seaborn 作为 sns 导入导入操作系统path_to ='Data \\ 2017-04 \\ MonthlyData \ q1analysis \ Energy Usage'#保存位置df = pd.read_csv('April2017NEW.csv',index_col = 1)df1 = df.loc ['输出能量,(Wh/h)']#选择指标值和平均值df1 ['Average'] = df1.mean(axis = 1)打印df1打印 df1['Average'].describe()定义历史():p = sns.distplot(df1 ['Average'],kde = False,bins = 25).set(xlim =(0,100));plt.xlabel('瓦特小时')plt.ylabel('家庭')返回 plt.show()

返回:

我想使用三种不同的颜色(低、中、高)来用图例表示 x = 轴上的较高值,如下所示:

我找到了以下示例:快到了.如何将范围分成 3 个,具有 3 种不同的颜色?

解决方案

解决方案:

N, bins, patch = plt.hist(df1['Average'], 30)cmap = plt.get_cmap('jet')低= cmap(0.5)中 =cmap(0.2)高= cmap(0.7)对于范围在(0,3)中的我:补丁[i] .set_facecolor(低)对于我在范围(4,13)中:补丁[i] .set_facecolor(medium)对于范围内的我(14,30):补丁[i] .set_facecolor(高)plt.xlabel("Watt Hours",fontsize = 16)plt.ylabel("家庭", fontsize=16)plt.xticks(字体大小=14)plt.yticks(字体大小=14)ax = plt.subplot(111)ax.spines ["top"].set_visible(False)ax.spines["right"].set_visible(False)plt.show()

输出:

I have this code, using a pandas df:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os


path_to = 'Data\\2017-04\\MonthlyData\q1analysis\Energy Usage'  # where to save

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)
print df1
print df1['Average'].describe()

def hist():
    p = sns.distplot(df1['Average'],kde=False, bins=25).set(xlim=(0, 100));
    plt.xlabel('Watt hours')
    plt.ylabel('Households')

    return plt.show()

which returns:

I would like to use three different colors (low, medium, high) to represent higher values on the x =axis with a legend, like this:

EDIT1:

I found this example: here, so I am trying to use this.

I've come up with this: Which is almost there. How does one split the range into 3, with 3 different colors?

解决方案

Solution:

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

cmap = plt.get_cmap('jet')
low = cmap(0.5)
medium =cmap(0.2)
high = cmap(0.7)


for i in range(0,3):
    patches[i].set_facecolor(low)
for i in range(4,13):
    patches[i].set_facecolor(medium)
for i in range(14,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()

output:

这篇关于Matplotlib/seaborn 直方图使用不同颜色的分组箱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆