Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controlling color order in seaborn

When using something like sns.barplot(myrange, means, pallette='deep') I get some order of colors. The order I see as default is blue, green, red, purple, brown, teal. If I have 6 bars everything is fine, but what if I want 12 bars and I want the first two bars to be blue, the next two to be green, next two to be red, and so on, such that groups are colored similarly?

I can just pass a list with color=myColors but this does not seem to accept html colors like #4C72B0 so I don't know how to get the exact hues I am looking for.

like image 442
The Nightman Avatar asked Dec 19 '22 01:12

The Nightman


1 Answers

First of all, there is no problem of supplying a hex color string to color argument of a seaborn barplot, e.g.

sns.barplot("A", "B", data=df, color="#4C72B0")

works fine. But it colorizes all barplots in the same color.

Hence you would want to use a palette. If you want to use the colors of an existing palette it is probably useful to start with exactly that palette and repeat it the number of times desired.

col = np.repeat(np.array(sns.color_palette("deep")),2,axis=0)
sns.barplot(..., palette=col)

Here we repeat it twice. Complete example:

import numpy as np
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

palette = np.repeat(np.array(sns.color_palette("deep")),2,axis=0)
n = 6
df = pd.DataFrame({"A":np.arange(n),
                   "B":np.random.rand(n)})
sns.barplot("A", "B", data=df, palette=palette)
plt.show()

enter image description here

In case you don't want to use an existing palette, you may also use your custom list of hex color strings to create one,

palette = sns.color_palette(["#4c72b0","#4c72b0","#55a868","#55a868","#c44e52","#c44e52"])

This would result in the same plot as above.

(Note that seaborn by default desaturates the colors. The colors of the bars are hence not exactly the colors from the palette; to change this behaviour one needs to set saturation=1 in the barplot call.)

like image 166
ImportanceOfBeingErnest Avatar answered Dec 27 '22 00:12

ImportanceOfBeingErnest