Skip to content

Instantly share code, notes, and snippets.

@Rekyt
Created March 12, 2015 18:17
Show Gist options
  • Save Rekyt/a7846af7c4c5fb5a48ea to your computer and use it in GitHub Desktop.
Save Rekyt/a7846af7c4c5fb5a48ea to your computer and use it in GitHub Desktop.
Snippet to assemble ggplot2 plots over several PDF pages with gridExtra
# Multipage pdf plots with ggplot2
library(ggplot2) # Load ggplot2 obviously
library(gridExtra) # Load some extensions to have multiplot pdf
# Simulate data
df = data.frame(x = seq(1:30), y = rnorm(30), z = runif(30, 1, 10))
# Example plots
p.1 = ggplot(df, aes(x = x, y = y)) +
geom_point()
p.2 = ggplot(df, aes(x = x, y = z)) +
geom_point()
p.3 = ggplot(df, aes(x = y, y = z)) +
geom_point()
p.4 = ggplot(df, aes(x = y)) +
geom_histogram()
plots.list = list(p.1, p.2, p.3, p.4) # Make a list of plots
# Generate plots to be saved to pdf, warning the argument to marrangeGrob
# have to be passed using do.call
# nrow (ncol) gives the number of rows (columns) of plots per page
# nrow and ncol have to be specificed inside a list
# Here, we'll obtain 2 plots in rows by page
plots = do.call(marrangeGrob, c(plots.list, list(nrow = 2, ncol = 1)))
# To save to file, here on A4 paper
ggsave("multipage_plot.pdf", plots, width = 21, height = 29.7, units = "cm")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment