首页 > 解决方案 > R中多个变量的高值和低值并排显示geom_boxplot?

问题描述

我正在尝试创建boxplot将在多个位置(即开始、中间、结束)比较obABTopLow值(在这种情况下为 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)

这是我想要实现的手动绘制的图形 在此处输入图像描述

标签: rggplot2boxplotfacet-wrapgridextra

解决方案


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

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

在此处输入图像描述

回应您的评论,我并不热衷于将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))

在此处输入图像描述


推荐阅读