#33 Control colors of boxplot | seaborn

This post gives 5 tips to manage the color of your seaborn boxplot:

Use a color palette

Python proposes several color palettes. You can call RColorBrewer palette like Set1, Set2, Set3, Paired, BuPu… There are also Sequential color palettes like Blues or BuGn_r. Read the great documentation of seaborn to learn more, and check the code below to understand how to apply it.

# library & dataset
import seaborn as sns
df = sns.load_dataset('iris')

# Use a color palette
sns.boxplot( x=df["species"], y=df["sepal_length"], palette="Blues")
#sns.plt.show()

 

Uniform color

Of course you can easily apply an uniform color to every boxes. Find a list of the numerous colors you can use here. The most common ones are b: blue
g
: green
r
: red
c
: cyan
m
: magenta
y
: yellow
k
: black
w
: white


import seaborn as sns
df = sns.load_dataset('iris')
sns.boxplot( x=df["species"], y=df["sepal_length"], color="skyblue")
#sns.plt.show()
Specific color for each group

import seaborn as sns
df = sns.load_dataset('iris')
my_pal = {"versicolor": "g", "setosa": "b", "virginica":"m"}
sns.boxplot( x=df["species"], y=df["sepal_length"], palette=my_pal)
#sns.plt.show()

 

Highlight a group

import seaborn as sns
df = sns.load_dataset('iris')
my_pal = {species: "r" if species == "versicolor" else "b" for species in df.species.unique()}
sns.boxplot( x=df["species"], y=df["sepal_length"], palette=my_pal)
#sns.plt.show()

 

Add transparency to color

I personally think that charts look better with transparency. I find out how to do it using the post of mwaskom on Github.


# import library and dataset
import seaborn as sns
df = sns.load_dataset('iris')

# usual boxplot
ax = sns.boxplot(x='species', y='sepal_length', data=df)

# Add transparency to colors
for patch in ax.artists:
 r, g, b, a = patch.get_facecolor()
 patch.set_facecolor((r, g, b, .3))

Leave a Reply

Your email address will not be published.