ggplot2 problems with using …prop… and grouping ba

2019-07-15 04:14发布

问题:

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)