ggplot2 problems with using …prop… and grouping bar graph by another category

心不动则不痛 提交于 2021-01-27 11:39:50

问题


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

In the following dataset, I am trying to create a bar graph that plots the percentage of the sample which have an Associate's, Master's, or PhD, separated by gender (done by using facet_grid() ). This is what I have generated so far:

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)

However, I would also like to display the difference between the groups "Audit" and "Credit" on each graph as side by bars. Yet, when I add "fill=category" to the aesthetics of ggplot, nothing changes:

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)

I realize that usually this is accomplished using geom_bar(stat="identity", position=position_dodge()) but when I change stat="identity", the following error message appears:

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

Any idea how to have a facet graph, use special characters such as ..prop.. AND add another fill to a ggplot2 graph?


回答1:


You could create the necessary four groups (instead of two) like this:

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) 



来源:https://stackoverflow.com/questions/48086575/ggplot2-problems-with-using-prop-and-grouping-bar-graph-by-another-categor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!