Home > OS >  Making stacked bar plots using ggplot2
Making stacked bar plots using ggplot2

Time:12-08

I am a bit new with making nice plots in R. Now I would like to make stacked bar plots. Here is the code for the stacked bar plots:

longer_data = structure(list(question = 
c("HMI1_Speed_and_distance_control", 
"HMI2_Supercruise_Speed_and_distance_control", 
"HMI3_Speed_and_distance_control", "HMI4_Speed_and_distance_control", 
"HMI5_Speed_and_distance_control", "HMI6_Speed_and_distance_control", 
"HMI1_Speed_and_distance_control", 
"HMI2_Supercruise_Speed_and_distance_control", 
"HMI3_Speed_and_distance_control", 
"HMI4_Speed_and_distance_control"), response = c(3L, 3L, 1L, 1L, 2L,
 1L, 2L, 3L, 1L, 3L)), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))
longer_data %>% 
  ggplot(aes(x = response))  
    geom_bar() 
    facet_wrap(vars(question), ncol = 3)  
    labs(x = "Response (on a 1 to 5 scale)", y = "Number of respondents")

I would like that the three bars per figure are put on top of each other and not next to each other. How do I do that?

Thanks!

CodePudding user response:

I created a factor variable and closed the facet wrap

    longer_data$question<- factor(longer_data$question)                     
    
    longer_data %>% 
      ggplot(aes( x=response, fill=question))  
      geom_bar(stat="count") 
     # facet_wrap(vars(question), ncol = 3)  
      labs(x = "Response (on a 1 to 5 scale)", y = "Number of respondents")

enter image description here

CodePudding user response:

I made guesses that 1 is Yes, 2 is No, and 3 is don't know, you should correct those if necessary.

longer_data %>% 
  mutate(response = factor(response, levels = 1:3, labels = c("Yes", "No", "Don't Know"))) %>%
  ggplot(aes(x = question, fill = response))  
  geom_bar() 
  scale_fill_manual(values = c("Yes" = "forestgreen", "No" = "firebrick2", "Don't Know" = "purple"))  
  theme(axis.text.x = element_text(angle = -90, hjust = 0))

enter image description here

  • Related