I would like to place two plots side by side using the ggplot2 package, i.e. 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?
qplot(displ, hwy, data=mpg, facets = . ~ year) + geom_smooth()
Best Answer
Any ggplots side-by-side (or n plots on a grid)
The function
grid.arrange()
in thegridExtra
package will combine multiple plots; this is how you put two side by side.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().
This will plot the output as a side effect. To print the side effect to a file, specify a device driver (such as
pdf
,png
, etc), e.g.or, use
arrangeGrob()
in combination withggsave()
,This is the equivalent of making two distinct plots using
par(mfrow = c(1,2))
. This not only saves time arranging data, it is necessary when you want two dissimilar plots.Appendix: Using Facets
Facets are helpful for making similar plots for different groups. This is pointed out below in many answers below, but I want to highlight this approach with examples equivalent to the above plots.
Update
the
plot_grid
function in thecowplot
is worth checking out as an alternative togrid.arrange
. See the answer by @claus-wilke below and this vignette for an equivalent approach; but the function allows finer controls on plot location and size, based on this vignette.