moondra moondra - 8 months ago 48
Python Question

Changing the colors of each hist facet on facetgrid?

I'm using the titanic dataset from kaggle, and I would like to differentiate the facets of Survivors (1) vs Non-Survivors (0) via different colors.

Here is my current FacetGrid:

enter image description here

The left facets(graphs) are of those who didn't survive. I want those to be colored in red. The right facets are fine the way the are at the moment.

So my desired output will look something like this.
I would also like to add a simple legend to each facet (red color = 'Died', blue color = 'Survived')
enter image description here

Here is a sample dataframe

Full Set

Sex Survived
1 male 0
2 female 1
3 female 1
4 female 1
5 male 0
6 male 0
7 male 0
8 male 0
9 female 1
10 female 1
11 female 1
12 female 1
13 male 0
14 male 0
15 female 0
16 female 1
17 male 0
18 male 1
19 female 0

Here is the code I currently have:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style ="ticks")
h=sns.FacetGrid(Full_set, col ='Survived', row ='Sex', palette = 'Set1', size =2, aspect =2)
h, 'Age')

I went through the FacetGrid's API in the documentation ( but I didn't see any examples or a way to do what I desire.

I tried
but the problem I was having was that on a hist, the graphs ended up overlapping, and fully covering the graph with lesser values.
Thank you!


The hue parameter works similar to a groupby object. So, when the hue is set according to the Survived column, it becomes a separate entity for it's unique values(namely, 0 and 1). Then using it's keywords arg, input the colors you want to display for each grouped instance(0→red, 1→blue).

d = {'color': ['r', 'b']}
g = sns.FacetGrid(df, row='Sex', col='Survived', hue_kws=d, hue='Survived', palette='Set1'), 'Age')