Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 views
in Technique[技术] by (71.8m points)

python - Matplotlib/seaborn histogram using different colors for grouped bins

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\MonthlyDataq1analysisEnergy 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:

enter image description here

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

enter image description here

EDIT1:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...