1

I am trying to save multiple ggplots that essentially do a histogram of each column. Ideally I would like to have 2 or 3 graphs per page, but for now I am fine with just 1 per page. The ggplots look fine, but I cannot seem to get the ggplots to save correctly(although probably not doing it correctly).

item_set <- unique(df$Item_number)
for(i in 1:length(item_set)){
  n <- as.character(item_set[i])
  temp <- wide_data[, grep(n, names(wide_data))]
  temp <- temp[, grep("Time", names(temp))]
  coln <- colnames(temp)
  
  ggplot(data = temp, aes_string(x = coln)) + geom_histogram(color = "black", fill = "white", bins = 70)
  ggsave("Time Spent - Entire Sample.pdf")
   
}

So for each ggplot, it is basically just taking column by column, by column name(coln) and creating a histogram. How can I save all of these to a single pdf?

Duba Minus
  • 21
  • 3
  • Please provide enough code so others can better understand or reproduce the problem. – Community Sep 05 '21 at 23:06
  • Does this answer your question? [Printing multiple ggplots into a single pdf, multiple plots per page](https://stackoverflow.com/questions/12234248/printing-multiple-ggplots-into-a-single-pdf-multiple-plots-per-page) – Paul Sep 06 '21 at 10:26

1 Answers1

0

Maybe you will find this example of creating ggplots in a loop useful.

# Plot separate ggplot figures in a loop.
library(ggplot2)

# Make list of variable names to loop over.
var_list = combn(names(iris)[1:3], 2, simplify=FALSE)

# Make plots.
plot_list = list()
for (i in 1:3) {
    p = ggplot(iris, aes_string(x=var_list[[i]][1], y=var_list[[i]][2])) +
        geom_point(size=3, aes(colour=Species))
    plot_list[[i]] = p
}

# Save plots to tiff. Makes a separate file for each plot.
for (i in 1:3) {
    file_name = paste("iris_plot_", i, ".tiff", sep="")
    tiff(file_name)
    print(plot_list[[i]])
    dev.off()
}

# Another option: create pdf where each page is a separate plot.
pdf("plots.pdf")
for (i in 1:3) {
    print(plot_list[[i]])
}
dev.off()