show multiple plots from ggplot on one page in r
You can save all the plot in a list
then use either cowplot::plot_grid()
or gridExtra::marrangeGrob()
to put them in one or more pages
See also:
Creating arbitrary panes in ggplot2 (
patchwork
,multipanelfigure
&egg
packages)Multiple plots in for loop
library(tidyverse)
# create a list with a specific length
plot_lst <- vector("list", length = 8)
for (i in 1:8) {
g <- ggplot(data = mtcars, aes(x = hp, y = wt)) +
geom_point()
plot_lst[[i]] <- g
}
# Combine all plots
cowplot::plot_grid(plotlist = plot_lst, nrow = 4)
library(gridExtra)
ml1 <- marrangeGrob(plot_lst, nrow = 2, ncol = 2)
ml1
Created on 2018-09-20 by the reprex package (v0.2.1.9000)
Plotting multiple plots on the same page using ggplot and for loop
i
in the for
loop is the dataset hence res_plot_list[[i]]
fails. Try -
for (i in seq_along(plots_list)) {
res_plot_list[[i]] <- residual_plots(plots_list[[i]])
}
Or why not just use lapply
-
res_plot_list <- lapply(plots_list, residual_plots)
Multiple plots on one page using ggplot
You might want to take a look at the cowplot
package that allows more flexibility than just using a naked grid.arrange
.
This works - albeit a bit inelegantly:
library(ggplot2)
library(grid)
library(gridExtra)
lg <- list()
for (i in 1:12) {
x <- 1:10
y <- 2*x + rnorm(x)
lg[[i]] <- qplot(x, y)
}
grid.arrange(lg[[1]],lg[[2]],lg[[3]],lg[[4]],lg[[5]],lg[[6]],nrow=3,ncol=2)
grid.arrange(lg[[7]],lg[[8]],lg[[9]],lg[[10]],lg[[11]],lg[[12]],nrow=3,ncol=2)
Another more elegant but somewhat obtuse way to do the grid.arrange
is the following (thanks to Axeman and beetroot - note the comments).
do.call(grid.arrange, c(lg[1:6], nrow = 3))
do.call(grid.arrange, c(lg[7:12], nrow = 3))
or this:
grid.arrange(grobs = lg[1:6], ncol=2)
grid.arrange(grobs = lg[7:12], ncol=2)
They all result in this - (think two of these - they look the same anyway):
multiple plots on a page
You can try this -
# number of plots
n <- 10
#Create a dataframe
x <- rnorm(50, mean = 20)
y <- 2*x + 1 + rnorm(50)
df <- data.frame(x = x, y = y)
pdf("test.pdf", onefile = TRUE)
#for n = 10, loop will run 3 times.
#It will generate 4, 4, and 2 plots
for(i in seq(ceiling(n/4))) {
#For the last page
if(n > 4) k <- 4 else k <- n
n <- n - 4
#Create a list to store the plots
plot_list <- vector('list', k)
for(j in 1:k) {
df$x <- df$x + rnorm(50, sd = 0.01)
df$y <- df$y + rnorm(50, sd = 0.01)
plot_list[[j]] <- ggplot(data = df) + aes(x, y) + geom_point()
}
#Print multiple plots together
print(do.call(gridExtra::grid.arrange, plot_list))
}
dev.off()
plotting multiple ggplots in a several page pdf (one or several plots per page)
The solution was actually pretty simple in the end...
### create a layout matrix (nrow and ncol will do the trick too, but you have less options)
layout_mat<-rbind(c(1,1,2),
c(1,1,3))
plots<-marrangeGrob(plot.list, layout_matrix=layout_mat)
ggsave( filename="mypdf.pdf", plots, width=29.7, height=21, units="cm")
This version actually gives you full control over plot sizes and uses the entire page!
R::ggplot2 Loop over vector of Y to make multiple plots at one page
I propose another solution based on this post.
Plotfunction <- function(y){my.plot <-
ggplot(df, aes_string(x = "x",
y = y,
group = "group",
color = "group")) +
geom_line()}
n <- ceiling(sqrt(length(my.s)))
do.call("grid.arrange",
c(lapply(my.s, Plotfunction), ncol = n, nrow = n))
drawing multiple plots, 2 per page using ggplot
If you just need to output plots with two per page, then I would use gridExtra
as was suggested above. You could do something like this if you were to put your ggplot objects into a list.
library(ggplot2)
library(shinipsum) # Just used to create random ggplot objects.
library(purrr)
library(gridExtra)
# Create some random ggplot objects.
ggplot_objects <- list(random_ggplot("line"), random_ggplot("line"))
# Create a list of names for the plots.
ggplot_objects_names <- c("This is Graph 1", "This is Graph 2")
# Use map2 to pass the ggplot objects and the list of names to the the plot titles, so that you can change them.
ggplot_objects_new <-
purrr::map2(
.x = ggplot_objects,
.y = ggplot_objects_names,
.f = function(x, y) {
x + ggtitle(y)
}
)
# Arrange each ggplot object to be 2 per page. Use marrangeGrob so that you can save two ggplot objects per page.
ggplot_arranged <-
gridExtra::marrangeGrob(ggplot_objects_new, nrow = 2, ncol = 1)
# Save as one pdf. Use scale here in order for the multi-plots to fit on each page.
ggsave("ggplot_arranged.pdf",
ggplot_arranged, scale = 1.5)
If you have a list of dataframes that you are wanting to create ggplots for, then you can use purrr::map
to do that. You could do something like this:
purrr::map(df_list, function(x) {
ggplot(data = x, aes(x = aData, y = bData)) +
geom_point(color = "steelblue", shape = 19)
})
Printing multiple ggplots into a single pdf, multiple plots per page
This solution is independent of whether the lengths of the lists in the list p
are different.
library(gridExtra)
pdf("plots.pdf", onefile = TRUE)
for (i in seq(length(p))) {
do.call("grid.arrange", p[[i]])
}
dev.off()
Because of onefile = TRUE
the function pdf
saves all graphics appearing sequentially in the same file (one page for one graphic).
Related Topics
R: Removing Null Elements from a List
Converting Data Frame Column from Character to Numeric
Scale and Size of Plot in Rstudio Shiny
Photo Alignment with Graph in R
Reset the Graphical Parameters Back to Default Values Without Use of Dev.Off()
Catching an Error and Then Branching Logic
Show Correlations as an Ordered List, Not as a Large Matrix
R: What Are Operators Like %In% Called and How to Learn About Them
Merging More Than 2 Dataframes in R by Rownames
How to Deal with Hdf5 Files in R
Undefined Columns Selected When Subsetting Data Frame