Search code examples
rggplot2geom-bar

Grouped bar chart in R with 4 bars for each group


So basically I am trying to figure out how to make a bar chart look like this in ggplot2 - and failing...

enter image description here

and this is my data

DF <- structure(list(Location = c("PC_of_recapped_cells", "PC_of_infested_cells", 
"PC_Recapped_and_Infested", "PC_Normal_mites"), S1 = c(7.31, 
3.2, 85.71, 85.71), S2 = c(7.46, 2.63, 83.33, 100), S3 = c(12.17, 
11.3, 30.77, 69.23), S4 = c(10.77, 5.72, 82.35, 76.47), C1 = c(6.59, 
0, 0, 0), C2 = c(15.94, 0, 0, 0), TS3 = c(14.97, 16.77, 25, 39.29
)), .Names = c("Location", "S1", "S2", "S3", "S4", "C1", "C2", 
"TS3"), class = "data.frame", row.names = c(NA, -4L))

"Error: col_names must be TRUE, FALSE or a character vector"


Solution

  • First do some manual cleanup in your text file by changing the spaces to commas:

    Location,S1,S2,S3,S4,C1,C2,TS3
    PC_of_recapped_cells,7.31,7.46,12.17,10.77,6.59,15.94,14.97
    PC_of_infested_cells,3.20,2.63,11.30,5.72,0.00,0.00,16.77
    PC_Recapped_and_Infested,85.71,83.33,30.77,82.35,0.00,0.00,25.00
    PC_Normal_mites,85.71,100.00,69.23,76.47,0.00,0.00,39.29
    

    Then you can load in the data using the tidyverse read_csv() function and reshape it as follows:

    library(tidyverse)
    df <-
      file_path %>% 
      read_csv() %>% 
      gather(key = type, value = pct, -Location) %>% 
      mutate(type = fct_relevel(type, c("S1", "S2", "S3", "S4", "C1", "C2", "TS3")))
    
    df
       Location                 type     pct
       <chr>                    <chr>  <dbl>
     1 PC_of_recapped_cells     S1      7.31
     2 PC_of_infested_cells     S1      3.2 
     3 PC_Recapped_and_Infested S1     85.7 
     4 PC_Normal_mites          S1     85.7 
     5 PC_of_recapped_cells     S2      7.46
     6 PC_of_infested_cells     S2      2.63
    ...
    

    Then it can be plotted:

    df %>% 
      ggplot(aes(x = type, y = pct, fill = Location)) + 
      geom_col(position = "dodge") +
      theme(legend.position = "bottom")
    

    You should be able to take it from there when it comes to recoloring, renaming labels and other changes.