user1357015
user1357015

Reputation: 11696

How to combine multiple ggplot2 objects on the same scale

Suppose I have the following data:

mymatrix1 <- matrix(data = 0, nrow = 105, ncol =2)
mymatrix2 <- matrix(data = 0, nrow = 108, ncol =2)
mymatrix3 <- matrix(data = 0, nrow = 112, ncol =2)

mymatrix1[,1] <- sample(0:1, 105, replace= TRUE)
mymatrix1[,2] <- rnorm(105, 52, 2)
mymatrix2[,1] <- sample(0:1, 108, replace= TRUE)
mymatrix2[,2] <- rnorm(108, 60, 2)
mymatrix3[,1] <- sample(0:1, 112, replace= TRUE)
mymatrix3[,2] <- rnorm(112, 70, 2)

for(i in 1:3){  colnames(mydata[[i]]) <- c("class", "readcount") }

mydata <- list(mymatrix1, mymatrix2,mymatrix3)

I get the plot for mydata[[1]] as I want it using the following:

qplot(class, readcount, data = as.data.frame(mydata[[1]]), geom="boxplot", fill = factor(class))+
  geom_jitter(position=position_jitter(w=0.1,h=0.1))+
  scale_x_continuous(breaks=c(0,1), labels=c("0", "1"))

Now, how would I get all the box plots next to each other (so iterate over the list)? Using grid.arrange? But that would give me different scales... what if I wanted the same scale? Can someone show both?

Upvotes: 0

Views: 374

Answers (1)

Jake Burkhead
Jake Burkhead

Reputation: 6545

Check out facet_wrap.

library(ggplot2)

mymatrix1 <- matrix(data = 0, nrow = 105, ncol =2)
mymatrix2 <- matrix(data = 0, nrow = 108, ncol =2)
mymatrix3 <- matrix(data = 0, nrow = 112, ncol =2)

mymatrix1[,1] <- sample(0:1, 105, replace= TRUE)
mymatrix1[,2] <- rnorm(105, 52, 2)
mymatrix2[,1] <- sample(0:1, 108, replace= TRUE)
mymatrix2[,2] <- rnorm(108, 60, 2)
mymatrix3[,1] <- sample(0:1, 112, replace= TRUE)
mymatrix3[,2] <- rnorm(112, 70, 2)

mydata <- list(mymatrix1, mymatrix2,mymatrix3)

for(i in 1:3){
    mydata[[i]] <- cbind(mydata[[i]], i)
    colnames(mydata[[i]]) <- c("class", "readcount", "group")
}


mydata <- as.data.frame(do.call(rbind, mydata))

## fixed scales
p <- qplot(class, readcount, data = mydata, geom="boxplot", fill = factor(class)) +
  geom_jitter(position=position_jitter(w=0.1,h=0.1)) +
  scale_x_continuous(breaks=c(0,1), labels=c("0", "1")) +
  facet_wrap(~ group)


## free scales
p + facet_wrap(~ group, scales = "free")

enter image description here enter image description here

Upvotes: 1

Related Questions