在R [重复]中显示ggplot条形图上的百分比

问题描述 投票:0回答:2

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

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

ggplot(data = iris) + 
  geom_bar(mapping = aes(x = Species, y = (..count..)/sum(..count..), fill = Species)) +
  scale_y_continuous(labels = percent)
r ggplot2 bar-chart percentage
2个回答
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
投票
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')
© www.soinside.com 2019 - 2024. All rights reserved.