saving multiple ggplots WITHOUT for loop

Perhaps, you are looking for this

dfs <- c("cars","pressure","mtcars")

my_plots <- list()
y.plot <- list()
en <- length(dfs)
y.plot <- lapply(1:en, function(i){
  df <- get(dfs[i])
  varname <- colnames(df)
  my_plots[[i]] <- ggplot(data=df,aes(x=x,y=y)) + geom_point() + 
    labs(x=varname[1], y=varname[2]) + theme_bw()

myplots <-, c(y.plot, ncol = en))

location <- "C:\\_My Work\\RStuff\\GWS\\"
ggsave(plot=myplots, file=paste0(location,"myplots.png"), width = 14, height = 10, units = "cm")

Please note that ggsave currently recognises the extensions eps/ps, tex (pictex), pdf, jpeg, tiff, png, bmp, svg and wmf (windows only).

If you wish to save it to a excel file, you need to save the image as a jpeg file and then use openxslx as shown below

ggsave(plot=myplots, file=paste0(location,"myplots.jpeg"), width = 14, height = 10, units = "cm")

pic_path <- paste0(location,"myplots.jpeg")

# Add to a new work book -------------
wb <- openxlsx::createWorkbook()
addWorksheet(wb, "Plots")
insertImage(wb, "Plots", pic_path)
openxlsx::saveWorkbook(wb, file=paste0(location,"myplots.xlsx"), overwrite = TRUE)

# Kill pic


CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top