Reputation: 23
I have something like the following:
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])}
The following command creates a boxplot for the 5 columns of matrix A:
boxplot(A[,1:5])
What I would like to do now is to have a boxplot like this, where each boxplot of a column of A is plotted next to a boxplot of the corresponding column of B. The boxplots should be directly next to each other, and between pairs of boxplots of the columns 1 to 5 there should be a small distance.
Thanks in advance!
Upvotes: 2
Views: 3880
Reputation: 83215
An implementation with dplyr
and 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()
which gives:
EDIT: To change the order of the boxes, you can use:
ggplot(AB, aes(x=var, y=value, fill=factor(set, levels=c("B","A")))) +
geom_boxplot() +
theme_bw()
which gives:
Upvotes: 3
Reputation: 8267
Bind your matrices together columnwise, inserting NA
columns:
C <- cbind(A[,1],B[,1])
for ( ii in 2:5 ) C <- cbind(C,NA,A[,ii],B[,ii])
(Yes, this is certainly not the most elegant way - but probably the simplest and easiest to understand.)
Then boxplot and add axis labels:
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)
Upvotes: 4