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()
The above solutions may not be efficient if you want to plot multiple ggplot plots using a loop (e.g. as asked here: Creating multiple plots in ggplot with different Y-axis values using a loop), which is a desired step in analyzing the unknown (or large) data-sets (e.g., when you want to plot Counts of all variables in a data-set).
The code below shows how to do that using the mentioned above 'multiplot()', the source of which is here: http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2):
Now run the function - to get Counts for all variables printed using ggplot on one page
One things to note is that:
using
aes(get(strX))
, which you would normally use in loops when working withggplot
, in the above code instead ofaes_string(strX)
will NOT draw the desired plots. Instead, it will plot the last plot many times. I have not figured out why - it may have to do theaes
andaes_string
are called inggplot
.Otherwise, hope you'll find the function useful.
There is also multipanelfigure package that is worth to mention. See also this answer.
Created on 2018-07-06 by the reprex package (v0.2.0.9000).
Using the patchwork package, you can simply use
+
operator:Update: This answer is very old.
gridExtra::grid.arrange()
is now the recommended approach. I leave this here in case it might be useful.Stephen Turner posted the
arrange()
function on Getting Genetics Done blog (see post for application instructions)Using
tidyverse
You can use the following
multiplot
function from Winston Chang's R cookbook