Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing color scale in seaborn bar plot

Tags:

python

seaborn

I would like to use seaborn bar plot for my data with a color scale according to the values in the Y-axis. For example, from this image, color changes from left to right according to a color palette:

enter image description here

But what I actually wanted is this same color scheme but in "vertical" instead of "horizontal". Is this possible? I've searched and tried to set the hue parameter to the Y-axis but it doesn't seem to work, how can I do it?

Thanks in advance.

like image 523
MrPedru22 Avatar asked Mar 28 '16 21:03

MrPedru22


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.

Which attribute helps to color the plots in Seaborn?

palette attribute is used to set the color of the bars. It helps to distinguish between chunks of data.

What is hue in SNS barplot?

hue : (optional) This parameter take column name for colour encoding. data : (optional) This parameter take DataFrame, array, or list of arrays, Dataset for plotting. If x and y are absent, this is interpreted as wide-form. Otherwise it is expected to be long-form.


2 Answers

Here a solution:

import numpy as np, matplotlib.pyplot as plt, seaborn as sns sns.set(style="whitegrid", color_codes=True)  titanic = sns.load_dataset("titanic") data = titanic.groupby("deck").size()   # data underlying bar plot in question  pal = sns.color_palette("Greens_d", len(data)) rank = data.argsort().argsort()   # http://stackoverflow.com/a/6266510/1628638 sns.barplot(x=data.index, y=data, palette=np.array(pal[::-1])[rank])  plt.show() 

Here the output: bar plot

Note: the code currently assigns different (adjacent) colors to bars with identical height. (Not a problem in the sample plot.) While it would be nicer to use the same color for identical-height bars, the resulting code would likely make the basic idea less clear.

like image 78
Ulrich Stern Avatar answered Sep 20 '22 10:09

Ulrich Stern


This solution uses the values as indices into the color palette; so that similar values get similar colors:

import seaborn as sns import numpy as np   def colors_from_values(values, palette_name):     # normalize the values to range [0, 1]     normalized = (values - min(values)) / (max(values) - min(values))     # convert to indices     indices = np.round(normalized * (len(values) - 1)).astype(np.int32)     # use the indices to get the colors     palette = sns.color_palette(palette_name, len(values))     return np.array(palette).take(indices, axis=0)   x = np.arange(10) y = np.random.random(10) sns.barplot(x, y, palette=colors_from_values(y, "YlOrRd")) 

Resulting in:

This

like image 31
Abdo B. Avatar answered Sep 20 '22 10:09

Abdo B.