Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export R plot to multiple formats

Tags:

plot

r

graphics

Since it is possible to export R plots to PDF or PNG or SVG etc., is it also possible to export an R plot to multiple formats at once? E.g., export a plot to PDF and PNG and SVG without recalculating the plot?

like image 402
Wouter Beek Avatar asked Jan 06 '18 21:01

Wouter Beek


People also ask

Is there a way to Export all plots in R?

One option is to click on the 'Export' button in the 'Plots' tab in RStudio as we described previously. You can also export your plots from R to an external file by writing some code in your R script.

How do I save a Ggplot file as a png?

In most cases ggsave() is the simplest way to save your plot, but sometimes you may wish to save the plot by writing directly to a graphics device. To do this, you can open a regular R graphics device such as png() or pdf() , print the plot, and then close the device using dev. off() .

How do I save a figure as a pdf in R?

First, in order to save a plot as PDF in R you will need to open the graphics device with the pdf function, create the plot you desire and finally, close the opened device with the dev. off function.

Where are plots saved in R?

Remember that your plot will be stored relative to the current directory. You can find the current directory by typing getwd() at the R prompt. You may want to make adjustments to the size of the plot before saving it. Consult the help file for your selected driver to learn how.


1 Answers

Without using ggplot2 and other packages, here are two alternative solutions.

  1. Create a function generating a plot with specified device and sapply it

    # Create pseudo-data
    x <- 1:10
    y <- x + rnorm(10)
    
    # Create the function plotting with specified device
    plot_in_dev <- function(device) {
      do.call(
        device,
        args = list(paste("plot", device, sep = "."))  # You may change your filename
      )
      plot(x, y)  # Your plotting code here
      dev.off()
    }
    
    wanted_devices <- c("png", "pdf", "svg")
    sapply(wanted_devices, plot_in_dev)
    
  2. Use the built-in function dev.copy

    # With the same pseudo-data
    # Plot on the screen first
    plot(x, y)
    
    # Loop over all devices and copy the plot there
    for (device in wanted_devices) {
      dev.copy(
        eval(parse(text = device)),
        paste("plot", device, sep = ".")  # You may change your filename
      )
      dev.off()
    }
    

The second method may be a little tricky because it requires non-standard evaluation. Yet it works as well. Both methods work on other plotting systems including ggplot2 simply by substituting the plot-generating codes for the plot(x, y) above - you probably need to print the ggplot object explicitly though.

like image 77
ytu Avatar answered Oct 31 '22 01:10

ytu