简体   繁体   中英

Making stacked bar plots using ggplot2

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!

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")

在此处输入图像描述

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))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM