我有类似以下内容:
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列的箱线图应有较小的距离。
提前致谢!
一个实现dplyr
和tidyr
:
# 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()
这使:
编辑:要更改框的顺序,可以使用:
ggplot(AB, aes(x=var, y=value, fill=factor(set, levels=c("B","A")))) +
geom_boxplot() +
theme_bw()
这使:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句