【问题标题】:Boxplot comparison of multiple dataset using facet_wrap functionality of ggplot2 in R?使用 R 中 ggplot2 的 facet_wrap 功能对多个数据集进行箱线图比较?
【发布时间】:2021-12-08 13:27:20
【问题描述】:

我有一个data.frame,如下所示。

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))

目标:

我想生成 3 个facetboxplot,其中facet 一个是比较O1, R1, and C1 的数据集。在facet 2 上,我希望看到boxplotO2, R2, and C2,同样也希望看到第三个facet

示例:

我正在寻找plot 喜欢的附件。示例情节是2 facet,而我正在寻找3 facet

【问题讨论】:

    标签: r dataframe ggplot2 tidyverse boxplot


    【解决方案1】:

    更新:

    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) 
    

    第一个答案: 像这样?

    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)
    

    【讨论】:

    • 类似于@TarJae。每个facet 都应该跨月比较数据集。这意味着,Facet1 应该比较一年中所有月份的O1,R1, and C1 的数据。同样,Facet 应该有一个比较 boxplotO2,R2,and C2
    • 下次试试。请看我的更新!
    • 正是我想要的。谢谢
    【解决方案2】:

    试试:

    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()) 
    

    【讨论】:

    • 如果您对每个方面都有一个独特的图例感兴趣,那么我建议您使用 gridExtra 库查看这个 SO 问题,您在其中 grid.arrange 您的地块而不是使用 facet_wrap:@987654322 @
    • 非常感谢您对此进行调查并为我的问题提供替代解决方案。
    猜你喜欢
    • 2015-10-03
    • 2021-10-04
    • 2013-07-15
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    相关资源
    最近更新 更多