如何计算ggplot中的比例?

时间:2018-09-10 23:38:07

标签: r ggplot2

我从中借用数据集的similar question有一个答案

我有

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

我正在尝试获得类似以下的内容

enter image description here

    StudentData %>% group_by(gender, degree, category) %>% 
summarise(tot = n()) %>% 
      group_by(gender) %>% mutate(prop = tot/sum(tot)) %>% 
      ggplot(., aes(x=degree, fill=category)) + 
      geom_col(aes(y=prop),  position=position_dodge()) +
      geom_text(aes(label=scales::percent(round(prop,2)), 
                    y=prop), vjust=-.5, position=position_dodge(.9)) +
      scale_y_continuous(limits=c(0,1),labels = scales::percent) +
      ylab("Percent of Sample") +
      facet_grid(~gender) 

我想我可以按gender分组。但是当我按性别分组时,ggplot似乎忽略了映射到fill的内容。

StudentData %>% 
  ggplot(., aes(x=degree, group=gender, fill=category)) + 
  geom_bar(aes(y=..prop..), stat="count", position=position_dodge()) +
  geom_text(aes(label=scales::percent(round(..prop..,2)), 
                y=..prop..), stat="count", vjust=-.5, position=position_dodge(.9)) +
  scale_y_continuous(limits=c(0,1),labels = scales::percent) +
  ylab("Percent of Sample") +
  facet_grid(~gender) 

enter image description here

0 个答案:

没有答案