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

在以下数据集中,我正在尝试创建一个条形图,该图绘制了具有副学士、硕士或博士学位的样本百分比,按性别分隔(使用 facet_grid() 完成)。这是我到目前为止生成的:

StudentData %>% ggplot(., aes(x=degree, group=gender)) + 
            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) +
            scale_y_continuous(limits=c(0,1),labels = scales::percent) +
            ylab("Percent of Sample") +
            facet_grid(~gender)

但是,我还想将每个图表上的“审计”和“信用”组之间的差异显示为并排条形。然而,当我将“fill=category”添加到 ggplot 的美学中时,没有任何变化:

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) +
            scale_y_continuous(limits=c(0,1),labels = scales::percent) +
            ylab("Percent of Sample") +
            facet_grid(~gender)

我意识到通常这是使用完成的,geom_bar(stat="identity", position=position_dodge())但是当我更改时stat="identity",会出现以下错误消息:

Error in FUN(X[[i]], ...) : object 'prop' not found

任何想法如何有一个方面图,使用特殊字符,如 ..prop .. 并向 ggplot2 图添加另一个填充?

4

1 回答 1

1

您可以像这样创建必要的四个group(而不是两个):

StudentData %>% 
  ggplot(., aes(x=degree, group=interaction(gender, category), 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) 

在此处输入图像描述

于 2018-01-03T23:46:53.697 回答