Search code examples
rggplot2facetgeom-bargeom-col

R facet with geom_col?


I have imported the below excel file into the RStudio enter image description here

My goal is to display in a facet of 4 different barplots with x axis representing the categorical variable of algorithms, and y displays the percentages each time as they are counted already in columns Question_1,2,3,4. I use this simple R code to plot just one barplot

ggplot(data = R_Analysis_draft, mapping = aes(x = algorithms,y = Question_1)) +
     geom_col()

How can I display all 4 in the same facet since they all have the same categorical variable algorithms putting a header on top of each one different Question and using the percentages?


Solution

  • You can use

    library(tidyverse)
    
    df %>% 
      pivot_longer(-algorithms) %>% 
      ggplot(aes(x = algorithms, y = value, fill = name)) +
      geom_col()
    

    enter image description here or

    df %>% 
      pivot_longer(-algorithms) %>% 
      ggplot(aes(x = algorithms, y = value, fill = name)) +
      geom_col(position = position_dodge())
    

    enter image description here

    For faceted plotting use

    df %>% 
      pivot_longer(-algorithms) %>% 
      ggplot(aes(x = algorithms, y = value)) +
      geom_col(position = position_dodge()) + 
      facet_wrap(name~.)
    

    enter image description here Data

    df = structure(list(algorithms = c("Alg_1", "Alg_2", "Alg_3", "Alg_4", 
    "Alg_5"), Question_1 = c(51L, 43L, 48L, 48L, 54L), Question_2 = c(49L, 
    35L, 53L, 39L, 63L), Question_3 = c(55L, 42L, 54L, 48L, 47L), 
        Question_4 = c(52L, 36L, 46L, 48L, 55L)), class = "data.frame", row.names = c(NA, 
    -5L))