Export R plot to multiple formats

前端 未结 2 814
猫巷女王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: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.

提交回复
热议问题