Matplotlib/seaborn histogram using different colors for grouped bins

前端 未结 4 1375
谎友^
谎友^ 2021-01-12 16:09

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\\\\Mon         


        
4条回答
  •  隐瞒了意图╮
    2021-01-12 16:19

    If you want to color specific divisions with specific colors and label them accordingly you can use the following code:

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

提交回复
热议问题