Home > Mobile >  Boxplot comparison of multiple dataset using facet_wrap functionality of ggplot2 in R?
Boxplot comparison of multiple dataset using facet_wrap functionality of ggplot2 in R?

Time:10-22

I have a data.frame like below.

library(tidyverse)
library(lubridate)

set.seed(129)

DF <- data.frame(Date = seq(as.Date("2001-01-01"), to = as.Date("2005-12-31"), by = "month"),
                 O1 = runif(60,1,5), R1 = runif(60,1,5), C1 = runif(60,1,5),
                 O2 = runif(60,1,5), R2 = runif(60,1,5), C2 = runif(60,1,5),
                 O3 = runif(60,1,5), R3 = runif(60,1,5), C3 = runif(60,1,5))

Target:

I would like to produced a 3 facet boxplot, where facet one be comparing dataset of O1, R1, and C1. On facet 2, i would like to see boxplot for O2, R2, and C2, and likewise for the 3rd facet.

Example:

I am looking for a plot like attached. the example plot is 2 facet while I am looking for a 3 facet.

enter image description here

CodePudding user response:

Try:

DF %>% 
  pivot_longer(-Date) %>% 
  mutate(month = factor(month.abb[month(Date)], month.abb),
         groups = readr::parse_number(name)) %>% 
  group_by(groups) %>% 
  mutate(facet_groups = paste0(unique(name), collapse = ","),
         name = fct_reorder(name, groups)) %>% 
  ggplot(aes(x = month, y = value, fill = name))   
  geom_boxplot()  
  facet_wrap(facet_groups ~ .,
             ncol = 1)  
  labs(y = "Monthly Precipitation",
       x = element_blank(),
       fill = element_blank()) 

enter image description here

CodePudding user response:

update:

DF1 <- DF %>% 
  as_tibble() %>% 
  mutate(Date= ymd(Date)) %>% 
  mutate(month = month(Date),
         year = year(Date)) %>% 
  pivot_longer(
    cols = -c(Date, month, year)
  ) %>% 
  mutate(facet = case_when(name %in% c("O1", "R1", "C1") ~ "facet1",
                           name %in% c("O2", "R2", "C2") ~ "facet2",
                           name %in% c("O3", "R3", "C3") ~ "facet3")) 

  ggplot(DF1, aes(x=factor(month), y=value))  
  geom_boxplot(aes(fill=name))  
  facet_wrap(.~facet, nrow = 3) 

enter image description here

First answer: Something like this?

library(tidyverse)
DF %>% 
  pivot_longer(
    cols = -Date
  ) %>% 
  mutate(facet = case_when(name %in% c("O1", "R1", "C1") ~ "facet1",
                           name %in% c("O2", "R2", "C2") ~ "facet2",
                           name %in% c("O3", "R3", "C3") ~ "facet3")) %>% 
  ggplot(aes(name, value))  
  geom_boxplot()  
  facet_wrap(.~facet, nrow = 3)

enter image description here

  • Related