How To Manually Specify Palette Colors in Seaborn

How to Specify Colors As a Dictionary in Seaborn Python?
How to specify your own color pallete Seaborn Python?

When we make a plot with Seaborn, say a scatterplot using Seaborn’s scatterplot and color the groups of the data using a grouping variable, Seaborn chooses suitable colors automatically. Sometimes you might like to change the default colors to colors of your choice.

In this post, we will see how to manually specify colors to a Seaborn plot as a dictionary. Let us first load the libraries needed to make the plot.

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

We will be using Penguins dataset from Seaborn’s built-in datasets.

penguins = sns.load_dataset("penguins")

First, let us make a scatterplot between two quantitative variables and color the data points using a categorical variable using the argument “hue” to Seaborn’s scatterplot() function.

plt.figure(figsize=(9,7))
sns.scatterplot( data= penguins,
               x="flipper_length_mm", y="bill_length_mm",
               hue="species",
               size="body_mass_g")

Seaborn has picked suitable colors to highlight the different groups of species in the data.

Seaborn Scatterplot with Default Color Palette

How To Specify Colors of your Choice to Seaborn?

If you have colors of your choice, we can manually specify palette colors of our choice and make scatterplot. In addition, we can be more specific and assign a specific color to each group in the categorical variable. We do that using dictionary for color and specify a color for each group.

In this example, we manually specify color for each species using species as key and color as values in a dictionary. We have used the Tableau color options available in Python using their names.

# color palette as dictionary
palette = {"Adelie":"tab:cyan",
           "Gentoo":"tab:orange", 
           "Chinstrap":"tab:purple"}

Once we have specified the colors of interest, we can use that palette color dictionary for “palette” argument in Seaborn’s scatterplot() function.

plt.figure(figsize=(9,7))
sns.scatterplot( data= penguins,
               x="flipper_length_mm", y="bill_length_mm",
               hue="species",
               size="body_mass_g",
               palette=palette)
plt.ylabel("Flipper Length", size=14)
plt.xlabel("Bill Length", size=14)
plt.savefig("How_to_specify_your_own_color_pallete_Seaborn_Python.png")

Now our scatter plot has the palette colors that we manually specified. In this example, we specified the colors using named color options in Python. We can also specify colors using color codes.

How to specify your own color palette Seaborn Python?

Exit mobile version