将R绘图导出为多种格式

6

由于R语言中的图表可以导出为PDF、PNG或SVG等格式,是否也可以将一个图表同时导出为多个格式呢?例如,将一个图表导出为PDF、PNG和SVG格式,而无需重新计算该图表。


不是使用基本图形,而是使用ggplot2包。 - Rui Barradas
3
即使使用ggplot2,我也会这么说。ggplot2和其他基于grid的解决方案创建的是一个绘图程序,然后再传递给打印引擎才能发送到设备上。每次打印时都需要重新计算它们。 - IRTFM
请问,您觉得有人的回答有用吗? - ytu
@ytu IINM,目前的答案似乎需要为每个输出设备重新计算图形?如果是这种情况,那么用户42给出了正确的答案,但是在评论中。 - Wouter Beek
我认为不完全是这样。如果你使用dev.copy,根据它的文档,它“将当前设备的图形内容复制到指定的设备”,即绘图不会重新计算,而是被复制。另一方面,sapply是一个在C级别进行迭代的函数(你可以在这里找到相关讨论:https://dev59.com/yV4b5IYBdhLWcg3wiSPV)。你可能称之为“重新计算”,但对于相同的任务,它通常比`for`循环快得多。 - ytu
2个回答

6

在不使用ggplot2和其他包的情况下,这里提供了两种替代方案。

  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()
    }
    
第二种方法可能有点棘手,因为它需要 非标准评估。但它同样有效。两种方法都适用于其他绘图系统,包括 ggplot2,只需将生成图形的代码替换为上面的 plot(x, y) 即可 - 你可能需要明确地 print ggplot 对象。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接