user147529
user147529

Reputation: 665

How to put Seaborn FacetGrid on plt.subplots grid and change title or xlabel

I am trying to create a distplot/kdeplot with hue as the target for multiple columns in my dataset. I am doing this by using kdeplot with a facetgrid and using the ax parameter to make it plot on on my plt.subplot figures. However, I am unable to get the title to change on the individual plot. I have tried g.fig.suptitle and ax[0,0].set_title but neither are working

df = sns.load_dataset('titanic')
fig, ax =  plt.subplots(2,2,figsize=(10,5))
g = sns.FacetGrid(df, hue="survived")
g = g.map(sns.kdeplot, "age",ax=ax[0,0])
g.fig.suptitle('age')
h = g.map(sns.kdeplot, "fare",ax=ax[0,1])
h.fig.suptitle('fare')
ax[0,0].set_title ='age'
ax[1,0].set_xlabel='fare'

I am getting this image. It seems to be changing a plot at the bottom which I don't want I am getting this image. It seems to be change a plot at the bottom which I don't want

By the way, I don't have to use Seaborn, matplotlib is also fine

Upvotes: 3

Views: 1415

Answers (1)

StupidWolf
StupidWolf

Reputation: 46978

If you want two density plots for age and fare, you can try to pivot it long and then apply the facetGrid:

import seaborn as sns
df = sns.load_dataset('titanic')

So the long format looks like this, it allows you to split on the variable column:

df[['survived','age','fare']].melt(id_vars='survived')

    survived    variable    value
0   0   age 22.00
1   1   age 38.00
2   1   age 26.00
3   1   age 35.00
4   0   age 35.00

And we plot:

g = sns.FacetGrid(df[['survived','age','fare']].melt(id_vars='survived'),
                  col="variable",sharex=False,sharey=False,hue="survived")
g.map(sns.kdeplot,"value")

enter image description here

Upvotes: 1

Related Questions