【问题标题】:grouped bar plot with percentages where variables are different across groupings带有百分比的分组条形图,其中变量在分组之间是不同的
【发布时间】:2020-03-02 12:34:17
【问题描述】:

使用这个例子,我可以绘制一个漂亮的分组条形图,表示三个分组(Associates、Masters、PhD)中财务协议(信贷、审计、免费)的百分比:

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】:

    您可以预先汇总数据并使用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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 2021-10-21
      • 2023-01-04
      • 1970-01-01
      • 2020-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多