分组条形图,其中百分比在各个组之间均不同

问题描述 投票:1回答:1

在这个例子中,我可以绘制一个漂亮的分组图,表示三个组(助理,硕士,博士)中财务协议(信用,审计,免费)的百分比:

StudentData <- data.frame(degree = sample( c("Associates", "Masters", "PhD"), 100, replace=TRUE),
                          category = sample( c("Audit", "Credit"), 100, replace=TRUE))

StudentData2 <- data.frame(degree = sample( c("PhD"), 50, replace=TRUE),
                          category = sample( c("Free"), 50, replace=TRUE))

StudentData<-rbind(StudentData,StudentData2)


ggplot(StudentData, aes(x=degree, group=category, fill=category)) + 
  geom_bar(aes(y=..prop..), stat="count", position=position_dodge()) +
  scale_y_continuous(limits=c(0,1),labels = scales::percent) +
  ylab("Percent of Sample")

[![在此处输入图片描述] [1]] [1]

但是百分比实际上是三个财务分组在各分组之间的分配方式。也就是说,任何采用“免费”计划的人都在做博士学位。

我想将百分比表示为每个分组中的百分比,而不是总数。通过查看:

summary(StudentData[StudentData$degree == "PhD",])

        degree     category 
 Associates: 0   Audit :18  
 Masters   : 0   Credit:14  
 PhD       :82   Free  :50

[我们看到只有50/82名博士生正在参加免费计划,所以我希望将能够反映这一点的分组条形改为Free:50/82 Credit:14/82 Audit:18/8

r ggplot2
1个回答
3
投票

您可以预先聚合数据并使用geom_col()代替geom_bar()

StudentData %>%
  count(degree, category) %>%
  group_by(degree) %>%
  mutate(prop = n/sum(n)) %>%
  ggplot(aes(x=degree, y = prop, fill=category)) + 
  geom_col(position=position_dodge()) +
  scale_y_continuous(limits=c(0,1),labels = scales::percent) +
  ylab("Percent of Sample")

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.