for loop to generate and save multiple ggplots in a separate file

My data (TransDat70) contains 103 variables total. The first 102 are named "V1" through "V102", the last variable is names "Time.Min".

I need to generate 102 ggplots of each variable (V1 through V102) against the variable "Time.Min". I then need to save all these ggplots in a separate file (pdf) preferably all next to/below one another for comparison purposes.

I tried using code that I was able to find online but none has worked for me so far.

Here is my code:

var_list = combn(names(TransDat70)[1: 102], 2, simplify = FALSE)
plot_list = list()

for (i in 1: 3) {
    p = ggplot(TransDat70, aes_string(x = var_list[[i]][1], y = var_list[[i]][2])) + geom_point()
    plot_list[[i]] = p
}

for (i in 1: 3) {
    plot70 = paste("iris_plot_", i, ".tiff", sep = "")
    tiff(plot70)
    print(plot_list[[i]])
    dev.off()
}

pdf("plots.pdf")

for (i in 1: 3) {
    print(plot_list[[i]])
}

dev.off()

Any suggestions?

Upvotes: 0

Views: 1938

Answers (1)

Harry
Harry

Reputation: 3412

If by separate you meant each plot in a separate file, how about this?

library(ggplot2)

# FAKE DATA AS EXAMPLE
TransDat70 <- data.frame(
  1:10,
  1:10,
  1:10,
  1:10,
  1:10
)

colnames(TransDat70) <- c('V1', 'V2', 'V3', 'V4', 'Time.Min')

for (i in 1:(length(TransDat70) - 1)) {
  p <- ggplot(TransDat70, aes_string(x = paste('V', toString(i), sep=''), y='Time.Min')) + geom_point()
  ggsave(paste('~/Desktop/plot_', i, '.pdf', sep=''), p)
}

See the ggsave documentation for more options.

If you meant to have them all in one big file, take a look at Printing multiple ggplots into a single pdf, multiple plots per page.

However, for that many plots it would make a likely make a huge file, which could be problematic to open, especially if you have many points in your plots. In that case it might be better to compare them as separate files.

Upvotes: 1

Related Questions