1

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?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Ziofil
  • 1,815
  • 1
  • 20
  • 30

1 Answers1

2

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

Sheldore
  • 37,862
  • 7
  • 57
  • 71
  • Perhaps I wasn't clear: I don't want the columns that don't belong to a given category to show up. So in the plot on the left I don't want tomato, pepper and apple. In the plot on the right I don't want tree and leaf. – Ziofil May 23 '20 at 13:18