将 R 图导出为多种格式

Wou*_*eek 6 graphics plot r

既然可以将 R 图导出为 PDF 、 PNG或SVG 等,是否也可以将 R 图一次性导出为多种格式?例如,将绘图导出为 PDF 、 PNG和SVG 而无需重新计算绘图?

ytu*_*ytu 6

在不使用ggplot2其他包的情况下,这里有两种替代解决方案。

  1. 创建一个函数,生成具有指定设备的绘图,并且sapply它

    # 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)
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用内置函数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()
    }
    
    Run Code Online (Sandbox Code Playgroud)

第二种方法可能有点棘手,因为它需要非标准评估。但它也有效。这两种方法都适用于其他绘图系统,包括ggplot2简单地用上面的绘图生成代码替换plot(x, y)- 但您可能需要print显式地使用 ggplot 对象。