【问题标题】:Matplotlib/seaborn histogram using different colors for grouped binsMatplotlib/seaborn 直方图使用不同颜色的分组箱
【发布时间】:2017-05-07 11:37:59
【问题描述】:

我有这段代码,使用 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()

返回:

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

编辑1:

我找到了这个例子:here,所以我正在尝试使用它。

我想出了这个: 几乎就在那里。如何将范围分成 3 种,用 3 种不同的颜色?

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    解决方案:

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

    输出:

    【讨论】:

    • 您的代码中有错误(图片中也有错误,请仔细查看!)。当您调用 range(0,3) 时,您会得到数字 0,1,2。没有3!因此,当您将这些补丁的 facecolor 设置为 low 时,您会错过索引为 3 的补丁。因此,要么使用 range(0,4) 表示低,使用 range(4,13) 表示中,或者使用 range(0,3)对于低和范围(3,13)对于中等。高也一样!
    【解决方案2】:

    我建议你使用 plt.hist() 函数 3 次,每次使用不同的颜色。您可以使用函数的range 参数设置每个直方图的范围。图例是通过使用label 参数随后调用plt.legend() 生成的。

    【讨论】:

    • 谢谢。我在这里是一个完整的初学者,无论如何你可以为此提供一个例子吗?
    【解决方案3】:

    不使用 cmap 的更具可读性的通用解决方案,因为您只需要 3 种颜色用于特定间隔。

    n, bins, patches = plt.hist(df1['Average'], 30)
    
    for c, p in zip(bins, patches):
        if c > 0 and c < 4:
            plt.setp(p, 'facecolor', 'green')
        elif c >= 4 and c < 14  :
            plt.setp(p, 'facecolor', 'blue')
        else c>=14:
            plt.setp(p, 'facecolor', 'yellow')
    
    plt.show()
    

    【讨论】:

      【解决方案4】:

      如果您想用特定颜色为特定分区着色并相应地标记它们,您可以使用以下代码:

      import matplotlib.pyplot as plt
      import numpy             as np
      import seaborn as sns; sns.set(color_codes=True)
      
      number_of_bins = 20
      N, bins, patches = plt.hist(np.random.rand(1000), number_of_bins, rwidth=0.8)
      
      #Define the colors for your pathces (you can write them in any format):
      colors    = [(0, 0, 0), "b", "#ffff00", "red"]
      #Define the ranges of your patches:
      divisions = [range(1), range(1, 9), range(9, 14), range(14, 20)]
      #If you want to label the regions/divisions:
      labels    = ["Black", "Blue", "Yellow", "Red"]
      
      #for each division color the parches according to the specified colors:
      for d in divisions:
          patches[list(d)[0]].set_label(labels[divisions.index(d)])
          for i in d:
              patches[i].set_color(colors[divisions.index(d)])
      
      
      plt.title("Plot Title")
      plt.xlabel("X label")
      plt.ylabel("Y label")
      plt.legend(title="Legend Title")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-04
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        • 2017-06-29
        • 1970-01-01
        • 2020-02-21
        • 1970-01-01
        相关资源
        最近更新 更多