首页 文章

一个图中多个标签的多个箱图

提问于
浏览
2

我有以下内容:

x <- 1:5
y <- 2:6

A <- matrix(NA,nrow=100,ncol=5)
for(i in 1:5){A[,i] <- rnorm(100,x[i],y[i])}

B <- matrix(NA,nrow=100,ncol=5)
for(i in 1:5){B[,i] <- runif(100,min=x[i],max=y[i])}

以下命令为矩阵A的5列创建一个箱线图:

boxplot(A[,1:5])

我现在要做的是有一个像这样的箱线图,其中A列的每个箱图都绘制在B的相应列的箱线图旁边 . 箱图应该直接相邻,并且在两对之间第1列至第5列的箱线图应该有一小段距离 .

提前致谢!

2 回答

  • 3

    dplyrtidyr 的实现:

    # needed libraries
    library(dplyr)
    library(tidyr)
    library(ggplot2)
    
    # converting to dataframes
    Aa <- as.data.frame(A)
    Bb <- as.data.frame(B)
    
    # melting the dataframes & creating a 'set' variable
    mA <- Aa %>% gather(var,value) %>% mutate(set="A")
    mB <- Bb %>% gather(var,value) %>% mutate(set="B")
    
    # combining them into one dataframe
    AB <- rbind(mA,mB)
    
    # creating the plot
    ggplot(AB, aes(x=var, y=value, fill=set)) +
      geom_boxplot() +
      theme_bw()
    

    给出:
    enter image description here


    编辑:要更改框的顺序,您可以使用:

    ggplot(AB, aes(x=var, y=value, fill=factor(set, levels=c("B","A")))) +
      geom_boxplot() +
      theme_bw()
    

    给出:
    enter image description here

  • 3

    按列方式将矩阵绑定在一起,插入 NA 列:

    C <- cbind(A[,1],B[,1])
    for ( ii in 2:5 ) C <- cbind(C,NA,A[,ii],B[,ii])
    

    (是的,这肯定不是最优雅的方式 - 但可能是最简单和最容易理解的方式 . )

    然后boxplot并添加轴标签:

    boxplot(C,xaxt="n")
    axis(1,at=1+3*(0:4),labels=rep("A",5),tick=FALSE)
    axis(1,at=2+3*(0:4),labels=rep("B",5),tick=FALSE)
    axis(1,at=1.5+3*(0:4),labels=1:5,line=2,tick=FALSE)
    

    boxplot

相关问题