How to display number of cases per group in a stacked bar plot?

eye*_*rrs 1 r ggplot2

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)) 
Run Code Online (Sandbox Code Playgroud)

which produces 这个图片.

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.

Maë*_*aël 5

使用position_fill(vjust = 0.5)并标记为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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述