Thomas Matthew
Thomas Matthew

Reputation: 2886

Change Box and Point Grouping Hue on Seaborn Boxplot

Lets create an sns boxplot, per the documentation:

import seaborn as sns
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")
ax = sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips, palette="Set3")

Produces a nice plot:

enter image description here

However, I want to be able to control each groups' colors. I would like show smoker "yes" group as gray boxes and grey outlier points, and I would like smoker "no" groups to appear with green boxes and green outlier points. How can I edit the underlying matplotlib ax object to change these attributes?

Upvotes: 1

Views: 7689

Answers (1)

Ulrich Stern
Ulrich Stern

Reputation: 11301

Changing the colors of the boxes seems best done by passing your own palette to boxplot(). For changing the colors of the outliers ("fliers") by group, this answer included a solution. Here the resulting code:

import seaborn as sns, matplotlib.pyplot as plt
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")
ax = sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips,
  palette=sns.color_palette(('.5', 'g')))

# each box in Seaborn boxplot is artist and has 6 associated Line2D objects
for i, box in enumerate(ax.artists):
  col = box.get_facecolor()
  # last Line2D object for each box is the box's fliers
  plt.setp(ax.lines[i*6+5], mfc=col, mec=col)

plt.show()

And the result: box plot with desired colors

Upvotes: 4

Related Questions