Boxplot across three timepoints in ggplot

I would like boxplots with all three timepoints in my data on the same plot

Data:

df<-
structure(list(ID = c("ED_001", "ED_002", "ED_003", "ED_004", 
"ED_005"), Color = c("Black", "White", "Black", "Black", "White"
), Data_t1 = c(150, 159, 160, 154, 187), Data_t2 = c(123, 124, 
125, 126, 140), Data_t3 = c(133, 135, 145, 150, 153)), class = c("spec_tbl_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -5L), spec = structure(list(
    cols = list(ID = structure(list(), class = c("collector_character", 
    "collector")), Color = structure(list(), class = c("collector_character", 
    "collector")), Data_t1 = structure(list(), class = c("collector_double", 
    "collector")), Data_t2 = structure(list(), class = c("collector_double", 
    "collector")), Data_t3 = structure(list(), class = c("collector_double", 
    "collector"))), default = structure(list(), class = c("collector_guess", 
    "collector")), skip = 1), class = "col_spec"))

I can plot the first timepoint easily enough:

df  %>% 
 ggplot(. , aes(x = as.factor(Color), y = Data_t1)) + 
    geom_boxplot()

But how do I also plot Data_t2 and Data_t3? I don't think facet_wrap is the right approach. Do I group_by timepoint, and if so how? I would prefer a dplyr solution if possible rather than melting the data into long format as I always come unstuck with long format. Thanks


It looks like you’ve noticed it’s easiest to work with the data if it’s in long format. Here’s the method with tidyr. I then use a facet to separate the different groups. What facet you use depends on how you want to compare them.

library(tidyverse)
df  %>% 
 pivot_longer(starts_with("Data")) %>%
 ggplot(. , aes(y = value, x= Color, group = Color)) + 
  geom_boxplot() +
  facet_grid(~name)

If you really wanted them all on the same plot without facets, you could create a dummy variable. You could play around with factors to order them how you wish.

df  %>% 
 pivot_longer(starts_with("Data")) %>%
 mutate(group_var = paste0(name, " - ", Color)) %>%
 ggplot(. , aes(y = value, x= group_var, group = group_var)) + 
    geom_boxplot()

Created on 2022-01-14 by the reprex package (v2.0.1)