I am trying to generate 10 pairs of plots with a few pairs per page of plots, and am using a for
loop to construct the pairs. However, the plots are sent to the device as separate plots instead of pages.
The MWE below has identical constructions for base graphics and ggplot
versions, but the base graphics works and ggplot
does not. What do I need to do to get the pagination correct in the second version?
library(ggplot2)
attach(mtcars)
# correct configuration
par(mfrow=c(2,2))
for (ii in 1:3){
vars <- c("wt", "disp", "wt")
plot(get(vars[ii]), mpg)
hist(get(vars[ii]))
}
# places each on separate plot
par(mfrow=c(2,2))
for (ii in 1:3){
vars <- c("wt", "disp", "wt")
p <- ggplot(mtcars, aes(get(vars[ii]), mpg)) + geom_point(size=4)
plot(p)
p <- ggplot(mtcars, aes(get(vars[ii]))) + geom_histogram()
plot(p)
}
detach(mtcars)
Here is one way to do it with
cowplot::plot_grid
. Theplot_duo
function usestidyeval
approach inggplot2 v3.0.0
To separate plots into multiple pages, we can use gridExtra::marrangeGrob