views:

702

answers:

4

I would like to place two plots side by side using the ggplot2 package (ie. do the equivalent of par(mfrow=c(1,2))). For example, I would like to have the following two plots show side-by-side with the same scale.

x <- rnorm(100)
eps <- rnorm(100,0,.2)
qplot(x,3*x+eps)
qplot(x,2*x+eps)

Do I need to put them in the same data.frame like in this example?

qplot(displ, hwy, data=mpg, facets = . ~ year) + geom_smooth()

Thanks!

+2  A: 

Yes, methinks you need to arrange your data appropriately. One way would be this:

X <- data.frame(x=rep(x,2),
                y=c(3*x+eps, 2*x+eps),
                case=rep(c("first","second"), each=100))

qplot(x, y, data=X, facets = . ~ case) + geom_smooth()

I am sure there are better tricks in plyr or reshape -- I am still not really up to speed on all these powerful packages by Hadley.

Dirk Eddelbuettel
+3  A: 

Using the reshape package you can do something like this.

library(ggplot2)
wide <- data.frame(x = rnorm(100), eps = rnorm(100, 0, .2))
wide$first <- with(wide, 3 * x + eps)
wide$second <- with(wide, 2 * x + eps)
long <- melt(wide, id.vars = c("x", "eps"))
ggplot(long, aes(x = x, y = value)) + geom_smooth() + geom_point() + facet_grid(.~ variable)
Thierry
+2  A: 

This post on Getting Genetics Done provides a simple solution: http://gettinggeneticsdone.blogspot.com/2010/03/arrange-multiple-ggplot2-plots-in-same.html

Jeromy Anglim
+1  A: 

The function grid.arrange() in the gridExtra package is made for this purpose.

plot1 <- qplot(...)
plot2 <- qplot(...)
sidebysideplot <- grid.arrange(plot1, plot2, ncol=2)

This is useful when the two plots are not based on the same data, for example if you want to plot different variables without using reshape().

David