Search code examples
rggplot2geom-bar

Ggplot how to add a breakdown for demographic variables


Say I have a database that looks like this:

UnnestQ3 <- data.frame(Q3 = c ("mail", "email", "mail", "mail", 
                                "Demonstration", "Videos (Ex: Youtube)",
                                "Podcast", "Podcast", "mail"), Gender = c ("male", "male", "female", "male", "female", "NA", "NA", "Other", "Male")

And a bar plot for the total number of responses for each Q3 category made by this:

library(ggplot2)
ggplot(UnnestQ3, aes(x = Q3)) +
  geom_bar(width = 0.75, fill = "blue") +
  theme_minimal(base_size = 10) +
   geom_text(aes(label = paste0(..count..,"(",round(..count..*100/nrow(UnnestQ3)), "%)")), stat = "count", vjust = 0, colour = "black") +
  coord_flip() +
  labs(x = "Communication Method") +
  labs(y = "Total Number of Responses (N)") 

If I wanted to split the bar graph by how many male, female, and others responded per category, how would I go about adding that to the graph? Also, as an aside, if anyone could help me align the counts and percentages better, I'd be hugely appreciative.

Thank you!


Solution

  • Thank you M.Viking. Adding fill = Gender to the aes worked.

    ggplot(UnnestQ3, aes(x = Q3, fill = Gender)) +
      geom_bar(width = 0.75) +
      theme_minimal(base_size = 10) +
      geom_text(aes(label = paste0(..count..," (", 
                                  round(..count..*100/nrow(UnnestQ3)), "%)"),
                   color = Gender), 
               stat = "count", vjust = 0,  
               position = position_stack(vjust = 0.5)) +
       scale_color_manual(values = c("black", "black", "black", "black", "black"),
                          guide = "none") +
       coord_flip() +
       labs(x = "Communication Method") +
       labs(y = "Total Number of Responses (N)") +
       labs(fill = "Gender") +
       scale_fill_viridis_d()