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

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

提交回复
热议问题