r/ggplot:计算组内条形图份额

r/ggplot: compute bar plot share within group

我正在使用 ggplot2 制作一个按一个变量分组并以份额报告的条形图。

我希望百分比是分组变量的百分比,而不是整个数据集的百分比。

例如,

library(ggplot2)
library(tidyverse)

ggplot(mtcars, aes(x = as.factor(cyl), 
               y = (..count..) / sum(..count..),
               fill = as.factor(gear))) + 
geom_bar(position = position_dodge(preserve = "single")) + 
geom_text(aes(label = scales::percent((..count..)/sum(..count..)),
        y= ((..count..)/sum(..count..))), stat="count") + 
theme(legend.position = "none")

产生这个输出:

我希望百分比(和条形高度)反映“cyl 内”的比例,而不是在整个样本中共享。这可能吗?这会涉及 stat 争论吗?

顺便说一句,如果可以将 geom_text 调用定位在相关柱上,那将是理想的。任何指导将不胜感激。

这是一种方法:

library(dplyr)
library(ggplot2)

mtcars %>%
  count(cyl, gear) %>%
  group_by(cyl) %>%
  mutate(prop = prop.table(n) * 100) %>%
  ggplot() + aes(cyl, prop, fill = factor(gear), 
                 label = paste0(round(prop, 2), '%')) + 
  geom_col(position = "dodge") + 
  geom_text(position = position_dodge(width = 2), vjust = -0.5, hjust = 0.5)