简体   繁体   中英

how to control the axes of individual subplots of seaborn 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:

数据框

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');

在此处输入图像描述

However, I'd like to exclude the objects that don't belong to a given category (ie 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?

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 eg 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);

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM