1

I am attempting to produce a stacked bar plot that has the fill color defined by a variable and also shows the number of cases represented by each of the filled sections.

Reproducible example:

library(tidyverse)

data(mpg)

ggplot(mpg,aes(manufacturer))+
  geom_bar(position = "fill",stat = "count",aes(fill=drv))+
  theme_classic()+
  theme(text = element_text(size=20),
        axis.text.x = element_text(angle = 45, 
                                   vjust = 0.5)) 

which produces this image.

Here is a paired-down version of what I would like to produce programmatically:

, where the

n=...

are centered on each groups filled section and display the number of cases per group (drv) in each category (manufacturer).

Additionally, I have tried (unsuccessfully) incorporating code from this post and this post, which seem close to what I want, but when I incorporate the code from this post the following error is thrown:

Error: StatBin requires a continuous x variable: the x variable is discrete.Perhaps you want stat="count"?

I am not sure why this error is thrown because I do define stat="count" in the geom_bar() function call.

Peter
  • 11,500
  • 5
  • 21
  • 31
eyemarrs
  • 33
  • 4

1 Answers1

5

Use position_fill(vjust = 0.5) and label with after_stat(count):

ggplot(mpg, aes(manufacturer, fill = drv)) +
  geom_bar(position = "fill", stat = "count")+
  geom_text(aes(label = paste0("n=", after_stat(count))), stat='count', position = position_fill(vjust = 0.5)) +
  theme_classic()

enter image description here

Maël
  • 45,206
  • 3
  • 29
  • 67
  • 1
    Note: semi-hidden plotting components like `..count..` are considered deprecated. This can be replaced in your code with the better documented `after_stat(count)`. – jdobres Apr 03 '22 at 15:42
  • On a _horizontal_ stacked bars the counts are reversed : what's on the left should be on the right and vice versa. Any help? – Julien Sep 05 '22 at 14:35
  • try `rev`, if it does not work, you can still do a new question – Maël Sep 05 '22 at 14:36