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

时间:2018-09-17 17:33:46

标签: r ggplot2 bar-chart percentage

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

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

ggplot(data = iris) + 
  geom_bar(mapping = aes(x = Species, y = (..count..)/sum(..count..), fill = Species)) +
  scale_y_continuous(labels = percent)

2 个答案:

答案 0 :(得分:2)

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在每个栏中将标签居中

答案 1 :(得分:1)

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')