How to set a different color to the largest bar in a seaborn barplot?

后端 未结 4 1496
终归单人心
终归单人心 2020-12-25 15:36

I\'m trying to create a barplot where all bars smaller than the largest are some bland color and the largest bar is a more vibrant color. A good example is darkhorse analyti

相关标签:
4条回答
  • 2020-12-25 15:59

    The other answers defined the colors before plotting. You can as well do it afterwards by altering the bar itself, which is a patch of the axis you used to for the plot. To recreate iayork's example:

    import seaborn
    import numpy
    
    values = numpy.array([2,5,3,6,4,7,1])   
    idx = numpy.array(list('abcdefg')) 
    
    ax = seaborn.barplot(x=idx, y=values) # or use ax=your_axis_object
    
    for bar in ax.patches:
        if bar.get_height() > 6:
            bar.set_color('red')    
        else:
            bar.set_color('grey')
    

    You can as well directly address a bar via e.g. ax.patches[7]. With dir(ax.patches[7]) you can display other attributes of the bar object you could exploit.

    0 讨论(0)
  • 2020-12-25 16:00

    Just pass a list of colors. Something like

    values = np.array([2,5,3,6,4,7,1])   
    idx = np.array(list('abcdefg')) 
    clrs = ['grey' if (x < max(values)) else 'red' for x in values ]
    sb.barplot(x=idx, y=values, palette=clrs) # color=clrs)
    

    enter image description here

    (As pointed out in comments, later versions of Seaborn use "palette" rather than "color")

    0 讨论(0)
  • 2020-12-25 16:01

    How I do this:

    import seaborn as sns
    import matplotlib.pyplot as plt
    import numpy as np
    
    bar = sns.histplot(data=data, x='Q1',color='#42b7bd')
    # you can search color picker in google, and get hex values of you fav color
    
    patch_h = []    
    for patch in bar.patches:
        reading = patch.get_height()
        patch_h.append(reading)
    # patch_h contains the heights of all the patches now
    
    idx_tallest = np.argmax(patch_h)   
    # np.argmax return the index of largest value of the list
    
    bar.patches[idx_tallest].set_facecolor('#a834a8')  
    
    #this will do the trick.
    

    I like this over setting the color prior or post by reading the max value. We don't have to worry about the number of patches or what is the highest value. Refer matplotlib.patches.Patch ps: I have customized the plots given here a little more. The above-given code will not produce the same result.

    0 讨论(0)
  • 2020-12-25 16:04

    [Barplot case] If you get data from your dataframe you can do these:

    labels = np.array(df.Name)
    values = np.array(df.Score) 
    clrs = ['grey' if (x < max(values)) else 'green' for x in values ]
    #Configure the size
    plt.figure(figsize=(10,5))
    #barplot
    sns.barplot(x=labels, y=values, palette=clrs) # color=clrs)
    #Rotate x-labels 
    plt.xticks(rotation=40)
    
    0 讨论(0)
提交回复
热议问题