Export R plot to multiple formats

前端 未结 2 815
猫巷女王i
猫巷女王i 2021-01-19 22:58

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., expo

相关标签:
2条回答
  • 2021-01-19 23:43

    Yes, absolutely! Here is the code:

    library(ggplot2)
    library(purrr)
    data("cars")
    p <- ggplot(cars, aes(speed, dist)) + geom_point()
    
    prefix <- file.path(getwd(),'test.')
    
    devices <- c('eps', 'ps', 'pdf', 'jpeg', 'tiff', 'png', 'bmp', 'svg', 'wmf')
    
    walk(devices,
         ~ ggsave(filename = file.path(paste(prefix, .x)), device = .x))
    
    0 讨论(0)
  • 2021-01-19 23:57

    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.

    0 讨论(0)
提交回复
热议问题