pheeper
pheeper

Reputation: 1527

Selecting colors from Seaborn palette

I have five distribution plots side by side and usually changed the color of each one using the color property. However, now I want to use Seaborn's husl palette and I can't figure out how to apply a color from the palette to each chart. I'm pretty sure this is something simply I'm just over looking.

# sns.set(style="white", palette="muted", color_codes=True)  
sns.set(style="white", palette="husl", color_codes=True)

# Set up the matplotlib figure
f, axes = plt.subplots(ncols=5, figsize=(15, 4))
sns.despine(left=True)

# Rating of 1
sns.distplot(df1[df1['rating']==1]['cost'], kde=False, color='c', ax=axes[0], axlabel="Rating of 1")

# Rating of 2
sns.distplot(df1[df1['rating']==2]['cost'], kde=False, color='k', ax=axes[1], axlabel='Rating of 2')

# Rating of 3
sns.distplot(df1[df1['rating']==3]['cost'], kde=False, color="g", ax=axes[2], axlabel='Rating of 3')

# Rating of 4
sns.distplot(df1[df1['rating']==4]['cost'], kde=False, color="m", ax=axes[3], axlabel='Rating of 4')

# Rating of 5
sns.distplot(df1[df1['rating']==5]['cost'], kde=False, color="b", ax=axes[4], axlabel='Rating of 5')

plt.setp(axes, yticks=[])
plt.tight_layout()

Upvotes: 8

Views: 18423

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339795

Seaborn provides an interface to the husl space via husl_palette. You may create a palette with as many colors as you have unique categories (here, "ratings"). Then, either index the palette or iterate over it. The latter is shown below.

import matplotlib.pyplot as plt
import seaborn as sns; sns.set(style="white")
import pandas as pd
import numpy as np

df = pd.DataFrame({"cost" : np.random.randn(600),
                   "rating" : np.random.choice(np.arange(1,6), size=600)})

ratings = np.unique(df.rating.values)
palette = iter(sns.husl_palette(len(ratings)))

f, axes = plt.subplots(ncols=len(ratings), figsize=(15, 4))
sns.despine(left=True)

for (n, rat), ax in zip(df.groupby("rating"), axes):

    sns.distplot(rat["cost"], kde=False, color=next(palette), ax=ax, axlabel=f"Rating of {n}")

plt.setp(axes, yticks=[])
plt.tight_layout()
plt.show()

enter image description here

Upvotes: 8

Related Questions