Search code examples
matplotlibhistogram

pyplot histogram, different color for each bar (bin)


I would like to have a different color for each bar in pyplot histogram.

FROM THIS:

import matplotlib.pyplot as plt
plt.rcParams['font.size'] = '20'

data = ['a', 'b', 'b', 'c', 'c', 'c']
plt.hist(data);

enter image description here

TO THIS:

enter image description here


Solution

  • One of the options is to use pyplot.bar instead of pyplot.hist, which has the option color for each bin.

    The inspiration is from: https://stackabuse.com/change-font-size-in-matplotlib/

    from collections import Counter
    import matplotlib.pyplot as plt
    plt.rcParams['font.size'] = '20'
    
    data = ['a', 'b', 'b', 'c', 'c', 'c']
    
    plt.bar( range(3), Counter(data).values(), color=['red', 'green', 'blue']);
    plt.xticks(range(3), Counter(data).keys());
    
    

    enter image description here

    UPDATE:

    According to @JohanC suggestion, there is additional optional using seaborn (It seems me the best option):

    import seaborn as sns 
    sns.countplot(x=data, palette=['r', 'g', 'b'])
    

    Also, there is a very similar question:

    Have each histogram bin with a different color