Search code examples
rdatabasechartsboxplotggboxplot

Grouped Boxplot in RStudio for correlated data


I have a database and I need to put it in a grouped boxplot graphic, I tried some things with R base and ggplot2, but it is worthless, i don't know if i have to reorganice the database, or maybe a have a code that works.

I need a graph like this

phe <- data.frame(
horario= c("6:30","12:00","18:00","6:30","12:00","18:00","6:30","12:00","18:00"),
s1= c(7.48,7.49,7.29,7.35,7.47,7.27,7.41,7.99,8.07),
s2= c(7.61,7.55,7.45,7.29,7.32,7.34,7.21,7.27,7.29),
s3= c(8.02, 8.07, 7.84, 7.74, 7.83, 7.89, 7.17, 7.13, 7.17),
s4= c(8.41,9.42,9.18,7.87,10.45,9.85,8.25,10.51,10.15),
s5= c(8.24,10.56,9.81,7.69,9.17,8.27,6.96,9.59,9.16),
s6= c(7.74,10.39,9.93,7.88,10.4,9.56,8.06,9.96,9.39),
s7= c(8.41,10.7,10.19,8.43,10.72,9.95,8.08,10.19,9.11),
s8= c(8.2,10.97,10.22,8.17,9.59,9.16,8.17,9.23,8.27))

ggplot(phe, aes(x=horario, y=s1,s2,s3,s4,s5,s6,s7,s8, fill=horario)) +
geom_boxplot() +
facet_wrap(. ~ horario, scales = 'free_x')

I tried with this dataframe but the boxplot wasn't what i need. I got this but it jus shows 1 week and axes weren't ok


Solution

  • When you write, aes(x=horario, y=s1,s2,s3,s4,s5,s6,s7,s8, fill=horario)), this isn't doing what you think it is. As the ggplot2::aes() docs state:

    The names for x and y aesthetics are typically omitted because they are so common; all other aesthetics must be named.

    Everything after s1 except fill is not named. It is not being passed to geom_boxplot() to draw.

    The key thing is to put your data in long form:

    phe_long <- tidyr::pivot_longer(
        phe,
        !horario,
        names_to = "week",
        names_transform = \(x) sub("s", "Week", x)
    )
    

    Then it's just a case of styling. This should get you most of the way there:

    ggplot(phe_long, aes(x = week, y = value, fill = week)) +
        geom_boxplot() +
        facet_wrap(. ~ horario, scales = "free_x", strip.position = "bottom") +
        theme_minimal(base_size = 14) +
        scale_fill_brewer(palette = "Dark2") +
        theme(
            axis.text.x = element_blank(),
            axis.title = element_blank(),
            strip.text = element_text(size = 16),
            panel.grid.major.x = element_blank(),
            legend.title = element_blank()
        )
    

    enter image description here