3

I wonder is it possible to plot stacked bar plot with seaborn catplot. For example:

import seaborn as sns
exercise = sns.load_dataset("exercise")
plot = exercise.groupby(['diet'])['kind'].value_counts(normalize=True).mul(100).reset_index(name='percentage%')
g = sns.catplot(x="diet", y="percentage%", hue="kind", data=plot, kind='bar')

enter image description here

I'd like to stack kind, but it seems catplot doesn't take 'stacked' parameter.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Osca
  • 1,588
  • 2
  • 20
  • 41

1 Answers1

2

You cannot do it using sns.barplot, i think the closest you can get is using sns.histplot:

import seaborn as sns
exercise = sns.load_dataset("exercise")
plot = exercise.groupby(['diet'])['kind'].value_counts(normalize=True).mul(100).reset_index(name='percentage')
g = sns.histplot(x = 'diet' , hue = 'kind',weights= 'percentage',
             multiple = 'stack',data=plot,shrink = 0.7)

enter image description here

StupidWolf
  • 45,075
  • 17
  • 40
  • 72
  • Why compute the value counts and pass them as a weight to histplot instead of letting histplot compute them for you? – mwaskom Mar 22 '21 at 15:45
  • Hi @mwaskom, yes something like `sns.histplot(x = 'diet' , hue = 'kind',multiple = 'stack',data=exercise,shrink = 0.7)` , but no sure how u normalize to percentages with the sns.histplot function... – StupidWolf Mar 22 '21 at 15:48