代码之家  ›  专栏  ›  技术社区  ›  Hydro

R中多个变量的高值和低值的并排geom_boxplot?

  •  1
  • Hydro  · 技术社区  · 5 年前

    我正在努力创造 boxplot 那会比较 ob vs A. B 在多个位置(即开始、中间、结束) Top Low 值(在这种情况下为10%)。我正在尝试使用 gather , facet_wrap , grid.arrange , ggplot 功能在 R 但不能把东西放在一起。这是我到目前为止的代码——如果能帮助我继续前进,我将不胜感激。

    library(tidyverse)
    library(gridExtra)
    
    DF_1 = data.frame(Ob = runif(100, 10,80), A = runif(100, 5, 90), B = runif(100, 3,85), loc = rep("Start",100))
    DF_2 = data.frame(Ob = runif(100, 10,80), A = runif(100, 5, 90), B = runif(100, 3,85), loc = rep("Mid",100))
    DF_3 = data.frame(Ob = runif(100, 10,80), A = runif(100, 5, 90), B = runif(100, 3,85), loc = rep("End",100))
    
    DF_1_Top = DF_1[order(DF_1$Ob,decreasing = TRUE),][1:10,]
    DF_1_Low = DF_1[order(DF_1$Ob,decreasing = FALSE),][1:10,]
    
    DF_2_Top = DF_2[order(DF_2$Ob,decreasing = TRUE),][1:10,]
    DF_2_Low = DF_2[order(DF_2$Ob,decreasing = FALSE),][1:10,]
    
    DF_3_Top = DF_1[order(DF_3$Ob,decreasing = TRUE),][1:10,]
    DF_3_Low = DF_1[order(DF_3$Ob,decreasing = FALSE),][1:10,]
    
    DF_Top = rbind(DF_1_Top, DF_2_Top, DF_3_Top)
    DF_Low = rbind(DF_1_Low, DF_2_Low, DF_3_Low)
    
    DF_T = gather(DF_Top, key = "Variable", value = "Value", - "loc")
    DF_L = gather(DF_Low, key = "Variable", value = "Value", - "loc")
    
    P1 = ggplot(DF_T, aes(x = Variable, y = Value))+
    geom_boxplot()+facet_wrap(~loc, nrow = 1)
    
    P2 = ggplot(DF_L, aes(x = Variable, y = Value))+
      geom_boxplot()+facet_wrap(~loc, nrow = 1)
    
    grid.arrange(P1,P2, nrow = 2)
    

    这是我想实现的手动绘制的图形 enter image description here

    1 回复  |  直到 5 年前
        1
  •  8
  •   eipi10    5 年前

    您可以将所有数据堆叠到一个数据帧中,并创建一个图形。例如:

    d = bind_rows(High=DF_Top, Low=DF_Low, .id='source') %>% 
      mutate(source=factor(source, levels=c("High","Low")))
    
    d %>% 
      gather(key, value, Ob:B) %>% 
      mutate(key = fct_relevel(key, "Ob")) %>% 
      ggplot(aes(key, value)) +
        geom_hline(yintercept=0) +
        geom_boxplot() +
        facet_grid(source ~ loc, switch="x") +
        labs(x="", y="") +
        scale_y_continuous(expand=expand_scale(mult=c(0.0, 0.02))) +
        theme_classic() +
        theme(strip.placement="outside", 
              strip.background.x=element_rect(colour=NA, fill=NA),
              strip.text.x=element_text(size=11, face="bold"))
    

    enter image description here

    针对你的评论,我并不热衷于搬家 key 一个传奇的标签,但是。。。

    d %>% 
      gather(key, value, Ob:B) %>% 
      mutate(key = fct_relevel(key, "Ob")) %>% 
      ggplot(aes(loc, value, colour=key)) +
        geom_hline(yintercept=0) +
        geom_boxplot() +
        facet_grid(source ~ ., switch="x") +
        labs(x="", y="", colour="") +
        scale_y_continuous(expand=expand_scale(mult=c(0.0, 0.02))) +
        theme_classic() +
        theme(legend.position="bottom",
              legend.box.margin=margin(t=-20))
    

    enter image description here