繁体   English   中英

使用 R 中 ggplot2 的 facet_wrap 功能对多个数据集进行 Boxplot 比较?

[英]Boxplot comparison of multiple dataset using facet_wrap functionality of ggplot2 in R?

我有一个如下所示的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 facet boxplot ,其中facet是比较O1, R1, and C1数据集。 在第facet 2 ,我希望看到O2, R2, and C2 boxplot ,同样对于第三个facet

例子:

我正在寻找像附件一样的plot 示例图是2 facet而我正在寻找3 facet

在此处输入图片说明

更新:

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)

在此处输入图片说明

尝试:

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

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM