How do I draw a ggplot2 with facet_wrap showing the percentages of each group rather than the total percentages?

I would like to draw a ggplot with facet_wrap that does not show the actual percentage of the table, but the percentage of the given answer in each group. I have to do this because I want to show which answer is the most chosen and most important for each group. The groups are not the same size.

Sample data:

group <- c(rep(c("Group1"), times = 10),rep(c("Group2"), times = 6),rep(c("Group3"), times = 4))
choice <- c(rep(c("a","b","c"),length.out = 10), "a","a","a","a","b","c","b","b","b","c")
df <- data.frame(cbind(group,choice))

      

It would be nice if I could not use the generic prop.t

but prop.c

for show in my plot, because it is important to show, for example, that 66.67% of group 2 prefers choice a.

library(gmodels)
CrossTable(choice, group, prop.chisq=FALSE, prop.t = TRUE, prop.c = TRUE, prop.r = FALSE, format = "SPSS")

      

This is for the plot:

library(ggplot2)
g <- ggplot(df, aes_string(x="group", fill="group")) +
            geom_bar(aes(y = (..count..)/sum(..count..)))+
            ylab("percent")
g + facet_wrap(~ choice)

      

This is how it looks so far

Now the first point shows: 20%, 20%, 0%, but should show 40%, 66.67% and 0% (the percentage of each person in the group who gave this answer).

For the second bar, show: 30%, 16.667% and 75%.

and third bar: 30%, 16.667% and 25%

Thank you for your help.

+3


source to share


1 answer


It's probably best to calculate the percentages ahead of time:

library(dplyr)
dfl <- df %>% 
  group_by(group,choice) %>% 
  summarise(n=n()) %>% 
  group_by(group) %>% 
  mutate(perc=100*n/sum(n))

ggplot(dfl, aes(x=group, y=perc, fill=group)) +
  geom_bar(stat="identity") +
  ylab("percent") + 
  facet_wrap(~ choice)

      

this gives: enter image description here




Another (and probably better) way to represent data is to use faces by group:

ggplot(dfl, aes(x=choice, y=perc, fill=choice)) +
  geom_bar(stat="identity") +
  ylab("percent") + 
  facet_wrap(~ group)

      

this gives: enter image description here

+9


source







All Articles