2
votes

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!

2
possible duplicate of Plot multiple boxplot in one graphuser3710546
You could try: library(reshape2);d2 <- cbind(melt(A), value2=melt(B)[,3]); library(ggplot2); dM <- melt(d2, id.var=c("Var1", "Var2")); dM$Var2 <- factor(dM$Var2); ggplot(dM, aes(x=Var2, y=value, fill=variable))+ geom_boxplot()+scale_fill_manual(values=c("blue", "red"))akrun

2 Answers

4
votes

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)

boxplot

3
votes

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: enter image description here


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: enter image description here