ggplot2 barplot - 在堆叠条内添加百分比标签但在 y 轴上保留计数

ggplot2 barplot - adding percentage labels inside the stacked bars but retaining counts on the y-axis

我创建了一个包含变量计数的堆叠条形图。我想保留这些作为计数,以便不同的条形大小代表不同的组大小。但是,在条形图中,我想添加显示每个堆栈比例的标签 - 以百分比表示。

我设法为每个组创建了堆叠计数图。我还创建了标签并且它们放置正确。我纠结的是如何计算那里的百分比?

我已经试过了,但出现错误:

dataex <- iris %>%
  dplyr::group_by(group, Species) %>%
  dplyr::summarise(N = n())
names(dataex)

dataex <- as.data.frame(dataex)
str(dataex)

ggplot(dataex, aes(x = group, y = N, fill = factor(Species))) +
  geom_bar(position="stack", stat="identity") +
  geom_text(aes(label = ifelse((..count..)==0,"",scales::percent((..count..)/sum(..count..)))), position = position_stack(vjust = 0.5), size = 3) +
  theme_pubclean()

Error in (count) == 0 : comparison (1) is possible only for atomic and list types

期望的结果:

好吧,刚刚找到答案...或解决方法。也许这会在将来帮助某人:计算 ggplot 之前的百分比,然后只使用该向量作为标签。

dataex <- iris %>%
  dplyr::group_by(group, Species) %>%
  dplyr::summarise(N = n()) %>%
  dplyr::mutate(pct = paste0((round(N/sum(N)*100, 2))," %")) 
names(dataex)

dataex <- as.data.frame(dataex)
str(dataex)

ggplot(dataex, aes(x = group, y = N, fill = factor(Species))) +
  geom_bar(position="stack", stat="identity") +
  geom_text(aes(label = dataex$pct), position = position_stack(vjust = 0.5), size = 3) +
  theme_pubclean()