Derek Krantz
Derek Krantz

Reputation: 487

saving multiple ggplots WITHOUT for loop

using ggsave and a for loop, I know I can save multiple ggplots onto an excel spreadsheet

For example from Save multiple ggplots using a for loop :

for (i in uniq_species) {

temp_plot = ggplot(data= subset(iris, Species == i)) + 
                 geom_point(size=3, aes(x=Petal.Length, y=Petal.Width )) + ggtitle(i)

ggsave(temp_plot, file=paste0("plot_", i,".png"), width = 14, height = 10, units = "cm")
}

But would I would like to do is avoid the loop, as I have a list of plots. Using lapply I have ( I presume) a list of plots:

y.plot = lapply(1:nrow(df), function(row)
{
  ...
}

my question is, is there a way to take y.plot from above, and shove all of the graphs in there onto one excel spreadsheet, without a loop?

something like: ggsave(pic_path,plot=y.plot,width = 20,height=20,units='cm')

but this doesn't work

Upvotes: 0

Views: 382

Answers (1)

YBS
YBS

Reputation: 21287

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)
  x=df[,1]
  y=df[,2]
  my_plots[[i]] <- ggplot(data=df,aes(x=x,y=y)) + geom_point() + 
    labs(x=varname[1], y=varname[2]) + theme_bw()
  
})

myplots <- do.call(grid.arrange, 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
unlink(pic_path)

output

Upvotes: 2

Related Questions