The ggplot2 package provides an excellent platform for data visualization. One (minor) drawback of this package is that combining ggplot images into one plot, like the par() function does for regular plots, is not a straightforward procedure. Fortunately, R user Stephen Turner has kindly provided a function called “arrange” that does exactly this. The function, taken from his blog, and an example of how it can be used is provided below.
vp.layout <- function(x, y) viewport(layout.pos.row=x, layout.pos.col=y)
arrange <- function(..., nrow=NULL, ncol=NULL, as.table=FALSE) {
dots <- list(...)
n <- length(dots)
if(is.null(nrow) & is.null(ncol)) { nrow = floor(n/2) ; ncol = ceiling(n/nrow)}
if(is.null(nrow)) { nrow = ceiling(n/ncol)}
if(is.null(ncol)) { ncol = ceiling(n/nrow)}
## NOTE see n2mfrow in grDevices for possible alternative
grid.newpage()
pushViewport(viewport(layout=grid.layout(nrow,ncol) ) )
ii.p <- 1
for(ii.row in seq(1, nrow)){
ii.table.row <- ii.row
if(as.table) {ii.table.row <- nrow - ii.table.row + 1}
for(ii.col in seq(1, ncol)){
ii.table <- ii.p
if(ii.p > n) break
print(dots[[ii.table]], vp=vp.layout(ii.table.row, ii.col))
ii.p <- ii.p + 1
}
}
}
library(ggplot2) ; library(grid)
p1 <- qplot(wt, mpg, data=mtcars)
p2 <- ggplot(diamonds, aes(price, colour = cut)) +
geom_density()
arrange(p1,p2)

You can get this functionality from the gridExtra package as well.
How do you add R codes to your blog?
Hi Yana,
I use the method described here: http://www.r-bloggers.com/r-syntax-highlighting-for-bloggers-on-wordpress-com/
I was wondering if it would be possible to add distribution of individual points within the density plots of “price”, a piece of cod will be much great.
I also like cod, but I am not sure what your question is.
If there is anything I am ever struggling to on with ggplot2, I go to these sites:
http://had.co.nz/ggplot2/
http://wiki.stdout.org/rcookbook/Graphs/
I’ve wondered how to do this. I’m surprised that there isn’t an existing function for this in ggplot2, but Hadley does talk about it toward the end of the ggplot book, so that confirms to me that I’m (we’re) not missing something.
The R Cookbook example is very similar:
http://wiki.stdout.org/rcookbook/Graphs/Multiple%20graphs%20on%20one%20page%20%28ggplot2%29/