Search code examples
rsvgsaver-corrplot

Saving displayed plots using for loop as SVG


How can I save an R plot that is only displayed in the "plots-pane" and not saved in the workspace?

Here simplified example on how I create my plot:

library(corrplot)
data(cars)
res.plot <- cor(cars)
par(mfrow=c(3,2))
for (i in 1:6) {
 corrplot(res.plot)
}

To save the resulting plot I can't use ggsave for example because I dont have the plot= input as the plot is not saved in the workspace.

This code doesn't work either:

data(cars)
res.plot <- cor(cars)
par(mfrow=c(3,2))
svg(filename=paste0("Rplot_",Sys.time(),".svg"), width = 8.27,height = 11.69)
for (i in 1:6) {
  corrplot(res.plot)
}
dev.off() 

The only solution I found so far is to use the "Export" dialog of R studio but as I need to export a lot of plots it would be a way faster to save them using code.

Any ideas?


Solution

  • You are trying to save a loop. Try this:

    library(corrplot)
    data(cars)
    res.plot <- cor(cars)
    par(mfrow=c(3,2))
    
    for (i in 1:6) {
      svg(filename=paste0("Rplot_",Sys.time(),".svg"), width = 8.27,height =   11.69)
      corrplot(res.plot)
      dev.off() 
    }
    

    Or all plots in the same panel:

    library(corrplot)
    res.plot <- cor(cars)
    svg(filename=paste0("Rplot_",Sys.time(),".svg"), width = 8.27,height = 11.69)
    par(mfrow=c(3,2))
    for (i in 1:6) {
      corrplot(res.plot)
    }
    dev.off()