Ziofil
Ziofil

Reputation: 2005

How to control the axes of individual subplots in catplot

Consider the following data:

df = pd.DataFrame([['green','tree',2],
                   ['green','leaf',3],
                   ['red','tomato',1],
                   ['red','pepper',5],
                   ['red','apple', 1]], columns=['color', 'object', 'value'])

The dataframe looks like this:

dataframe

I'd like to use seaborn.catplot to produce a barplot of the various categories:

sns.catplot(data=df, kind='bar', x='object', y='value', col='color');

enter image description here

However, I'd like to exclude the objects that don't belong to a given category (i.e. in the first graph I want to exclude 'tomato', 'pepper' and 'apple', while in the second plot I want to exclude 'tree' and 'leaf'). How can I achieve this?

Upvotes: 1

Views: 1234

Answers (1)

Sheldore
Sheldore

Reputation: 39052

One way is to use seaborn's bar plot. I am creating two new columns based on your condition. You can then set the titles using for e.g. ax1.set_title

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 3))

mask = (df.color == 'green')

sns.barplot(x='object', y='value', data=df[mask], ax=ax1)
sns.barplot(x='object', y='value', data=df[~mask], ax=ax2)

ax1.set_title("color=green")
ax2.set_title("color=red")

You can also use catplot but that generates additional figures which you need to then close.

sns.catplot(data=df[mask], kind='bar', x='object', y='value', col='color', ax=ax1);
sns.catplot(data=df[~mask], kind='bar', x='object', y='value', col='color', ax=ax2);

enter image description here

Upvotes: 2

Related Questions