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

Question:

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 analytic’s pie chart gif where they break down a pie chart and end with a more clear barplot. Any help would be appreciated, thank you!

Asked By: pmdaly

||

Answers:

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

Answered By: iayork

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

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.

Answered By: Nico

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 = [patch.get_height() for patch in bar.patches]   
# 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
My results
ps: I have customized the plots given here a little more. The above-given code will not produce the same result.

Answered By: Jihjohn
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.