将R图导出为多种格式

时间:2018-01-06 21:38:36

标签: r plot graphics

由于可以将R图输出为PDF PNG SVG等,是否也可以将R图输出为多种格式 at一旦?例如,将情节导出为PDF PNG SVG,而无需重新计算情节?

2 个答案:

答案 0 :(得分:0)

是的,绝对!这是代码:

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))

答案 1 :(得分:0)

不使用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)
    
  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()
    }
    
  3. 第二种方法可能有点棘手,因为它需要non-standard evaluation。但它也有效。这两种方法都适用于其他绘图系统,包括ggplot2,只需将上面的plot(x, y)的绘图生成代码替换 - 您可能需要明确地print ggplot对象。