How to make a boxplot on ggplot with two columns for my x-axis and two columns for my y-axis?

Viewed 270

I am trying to make a grouped boxplot on ggplot, however, I am running into a problem since I have two columns for my x-axis and two columns for my y-axis and it won't let me plot it.

I know that if I have 1 x-axis and two y-axis I can use the gather function such as:

`BB <- BB %>%
  gather(key = "Type", value = "KO.Values", MetaT, 
         MetaG) %>%
  convert_as_factor(Type)
ggplot(BB, aes(x=Ocean.region, y=KO.Values, fill=Type)) + 
  geom_boxplot()+
  scale_fill_brewer(palette="Set1")+
  scale_y_log10()`

However, this isn't working since I have two x-axis as well. Also the Ocean.regionG and MetaG column are shorter than the Ocean.regionT and Meta T columns.

Any help would be greatly appreciated thank you!

Here are the first 10 rows of my dataset.

` Ocean.regionT Ocean.regionG       MetaT       MetaG
            AO            AO 0.000000000 0.000530614
            AO            AO 0.006962999 0.002265703
            AO            AO 0.123946517 0.001184657
    Madagascar            MS 0.081058488 0.024913063
    Madagascar            MS 0.049421702 0.008098015
            MS            MS 0.072319800 0.016901097
            MS            MS 0.035732418 0.075799616
            MS           NAO 0.029748322 0.037194669
            MS           NAO 0.021146596 0.041375374
           NAO           NAO 0.567529831 0.035902832
           NAO           NAO 0.602152447 0.013699213
           NAO           NAO 0.811603574 0.052514921`
1 Answers

It may be better to reshape with pivot_longer as it is more generalized and can reshape based on the pattern in column name. Here, we specify the names_sep with a regex lookaround to match between the last upper case letter and the lower case letter in column names, then use ggplot with 'x' as 'Ocean.region' and the fill as 'grp' column which include the suffix 'T', 'G'

library(dplyr)
library(tidyr)
library(ggplot2)
BB %>%
   pivot_longer(cols = everything(), names_to = c(".value", "grp"), 
       names_sep="(?<=[a-z])(?=[TG]$)") %>% 
   ggplot(aes(x = Ocean.region, y = Meta, fill = grp)) + 
       geom_boxplot() +
       scale_fill_brewer(palette="Set1") +         
       scale_y_log10()

-output

enter image description here

data

BB <- structure(list(Ocean.regionT = c("AO", "AO", "AO", "Madagascar", 
"Madagascar", "MS", "MS", "MS", "MS", "NAO", "NAO", "NAO"), 
Ocean.regionG = c("AO", 
"AO", "AO", "MS", "MS", "MS", "MS", "NAO", "NAO", "NAO", "NAO", 
"NAO"), MetaT = c(0, 0.006962999, 0.123946517, 0.081058488, 0.049421702, 
0.0723198, 0.035732418, 0.029748322, 0.021146596, 0.567529831, 
0.602152447, 0.811603574), MetaG = c(0.000530614, 0.002265703, 
0.001184657, 0.024913063, 0.008098015, 0.016901097, 0.075799616, 
0.037194669, 0.041375374, 0.035902832, 0.013699213, 0.052514921
)), class = "data.frame", row.names = c(NA, -12L))
Related