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

后端 未结 4 1497
终归单人心
终归单人心 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.

提交回复
热议问题