Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 245
pmdaly Avatar asked Jun 26 '15 13:06

pmdaly


People also ask

How do I change my bar color in seaborn?

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.

How do I make each color bar different in matplotlib?

You can change the color of bars in a barplot using color argument. RGB is a way of making colors. You have to to provide an amount of red, green, blue, and the transparency value to the color argument and it returns a color.

How do you set a barplot color?

To set colors for bars in Bar Plot drawn using barplot() function, pass the required color value(s) for col parameter in the function call. col parameter can accept a single value for color, or a vector of color values to set color(s) for bars in the bar plot.


2 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")

like image 168
iayork Avatar answered Sep 19 '22 15:09

iayork


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.

like image 37
Nico Avatar answered Sep 20 '22 15:09

Nico