Home > database >  Display percentages within category and also for entire sample with ordinal variable in facets
Display percentages within category and also for entire sample with ordinal variable in facets

Time:06-09

I'm trying to modify @DaveArmstrong 's answer to enter image description here

CodePudding user response:

Adding my own solution after playing around with the answer from another question that @tjebo provided:

d2 <- d %>%
  select(question1, question2, question3) %>% 
  pivot_longer(everything(), names_to = "question", values_to = "vals") %>% 
  group_by(question, vals) %>% 
  tally() %>% 
  group_by(question) %>% 
  mutate(pct = n/sum(n), race = "All")

d3 <- d %>%
  pivot_longer(-race, names_to = "question", values_to = "vals") %>% 
  group_by(question, race, vals) %>% 
  tally() %>% 
  group_by(question, race) %>% 
  mutate(pct = n/sum(n)) 

bind_rows(d2, d3) %>% 
ggplot(aes(x=race, y=pct, fill=as.factor(vals)))   
  geom_bar(position="dodge", stat="identity")   
  facet_wrap(~question)   
  scale_y_continuous(labels = scales:::percent)   
  labs(x="", 
       y="Percentage", 
       fill="Response")   
  theme_bw()   
  theme(legend.position = "top", 
        panel.grid = element_blank(), 
        axis.text.x = element_text(angle = 45, hjust=1))

enter image description here

  • Related