将R绘图导出为多种格式 [英] Export R plot to multiple formats

查看:189
本文介绍了将R绘图导出为多种格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于可以将R绘图导出为PDF PNG SVG等,因此也可以将R绘图导出为多种格式一次?例如,将图导出到PDF PNG SVG,而无需重新计算图?

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., export a plot to PDF and PNG and SVG without recalculating the plot?

推荐答案

在不使用ggplot2和其他软件包的情况下,这是两个替代解决方案.

Without using ggplot2 and other packages, here are two alternative solutions.

  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)

  • 使用内置功能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对象.

    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.

    这篇关于将R绘图导出为多种格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆