在 R 中的 ggplot 条形图上显示百分比

Display Percentage on ggplot Bar Chart in R

我需要在 R 中的条形图的条上显示百分比值。

此代码绘制分类数据,类别在 x 上,百分比在 y 上。如何对其进行修改,使其 在条形图本身 上显示百分比,而不仅仅是在 y 轴上?

ggplot(data = iris) + 
  geom_bar(mapping = aes(x = Species, y = (..count..)/sum(..count..), fill = Species)) +
  scale_y_continuous(labels = percent)
ggplot(data = iris, aes(x = factor(Species), fill = factor(Species))) +
geom_bar(aes(y = (..count..)/sum(..count..)),
         position = "dodge") + 
geom_text(aes(y = (..count..)/sum(..count..), 
              label = paste0(prop.table(..count..) * 100, '%')), 
          stat = 'count', 
          position = position_dodge(.9), 
          size = 3)+ 
labs(x = 'Species', y = 'Percent', fill = 'Species')

ggplot 中的 ..count.. 助手对于简单的情况可能很有用,但通常最好先在适当的级别聚合数据,而不是在您的 ggplot 调用中:

library(tidyverse)
library(scales)

irisNew <- iris %>% group_by(Species) %>% 
 summarize(count = n()) %>%  # count records by species
 mutate(pct = count/sum(count))  # find percent of total

ggplot(irisNew, aes(Species, pct, fill = Species)) + 
  geom_bar(stat='identity') + 
  geom_text(aes(label=scales::percent(pct)), position = position_stack(vjust = .5))+
  scale_y_continuous(labels = scales::percent)

vjust = .5 将每个栏中的标签居中