r - 保存绘图而不显示它

标签 r ggplot2 rstudio

是否可以保存绘图而不显示它?

我做了一点 ggplot hack 能够将图形复制到 powerpoint很容易,它将情节复制到剪贴板,但是可以看到设备窗口快速打开和关闭,这有点尴尬,我可以避免这种情况吗?

我正在使用 windowsrstudio .

可重现代码:

library(ggplot)

`-.gg` <- function(e1,e2){
  assertthat::assert_that(is.numeric(e2),
                          length(e2)<= 2)
  if(identical(e2,0)) return(invisible(NULL))
  W <- 8
  H <- 4.5
  dev.new(width=W * head(e2,1), height=H * tail(e2,1),noRStudioGD =TRUE)
  print(e1)
  savePlot("clipboard", type="wmf")
  dev.off()
  e1
}

ggplot(data.frame(x=1:10,y=1:10),aes(x,y)) + geom_point() - 1 - 0

编辑:

我的代码和选择的解决方案在处理半透明方面存在问题。大部分时间都可以,但异常(exception)情况会很烦人。
也许通向通用解决方案的途径是使用 tempfile 保存它然后通过适当的 R 函数或使用命令行使用 system 将其读入剪贴板(也许会在无形中打开文件并进行复制)。

最佳答案

这适用于 Windows:使用 win.metafile()设备。如果你没有给出文件名,它会保存到剪贴板。所以你的功能应该是

library(ggplot2)

`-.gg` <- function(e1,e2){
  assertthat::assert_that(is.numeric(e2),
                          length(e2)<= 2)
  if(identical(e2,0)) return(invisible(NULL))
  W <- 8
  H <- 4.5
  win.metafile(width=W * head(e2,1), height=H * tail(e2,1))
  print(e1)
  dev.off()
  e1
}

ggplot(data.frame(x=1:10,y=1:10),aes(x,y)) + geom_point() - 1 - 0

关于r - 保存绘图而不显示它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47221639/

相关文章:

r - 有没有办法强制 ode() [deSolve-R 包] 在 ode 函数中的每个积分步骤提供输出

r - 具有position_stack的抖动文本/标签

r - 在 R (ggplot) 中注释公式(使用 bqoute 或替代)给出错误

linux - 在 RStudio 上安装 R 的 TSA 包时出错

r - 如何使用 stringr 和 regex 转换字符串(更改、保留、提取),但有一些异常(exception)?

r - R 中的 lower.tri() 示例

r - 从列表中的数据框名称将标题名称添加到 ggplots 列表

r - ggplot : Order bars in faceted bar chart per facet

r - 无法在 CentOS 6.4 上安装 RStudio

R 包 "translateR"和 Microsoft API