如何从 RStudio 中的查看器将绘图保存为磁盘上的图像?

How to save a plot as image on disk from Viewer in RStudio?

总结:我的最终目标是使用 rCharts,特别是 Highcharts,作为 ReporteRs PowerPoint 报告自动化工作流程的一部分。我想使用的其中一个图表在 Rstudio 的查看器窗格中呈现为 html,并且 addPlot(function() print(myChart)) 不会将其添加到 PowerPoint。作为一种解决方法,我决定尝试将 myChart 保存到磁盘,这样我就可以将它添加到 PowerPoint 中。

所以我的问题真的是,如何将我的 html 图像放入我的 ReporteRs 工作流程? 要么将它保存到磁盘,要么让 ReporteRs 可读可以解决我的问题。

这道题真的和this one, but I'm using rCharts, specifically the example found 一样:

#if the packages are not already installed
install.packages('devtools')
require(devtools)
install_github('rCharts', 'ramnathv')

#code creates a radar chart using Highcharts
library(rCharts)
#create dummy dataframe with number ranging from 0 to 1
df<-data.frame(id=c("a","b","c","d","e"),val1=runif(5,0,1),val2=runif(5,0,1))
#muliply number by 100 to get percentage
df[,-1]<-df[,-1]*100

myChart <- Highcharts$new()
myChart$chart(polar = TRUE, type = "line",height=500)
myChart$xAxis(categories=df$id, tickmarkPlacement= 'on', lineWidth= 0)
myChart$yAxis(gridLineInterpolation= 'circle', lineWidth= 0, min= 0,max=100,endOnTick=T,tickInterval=10)
myChart$series(data = df[,"val1"],name = "Series 1", pointPlacement="on")
myChart$series(data = df[,"val2"],name = "Series 2", pointPlacement="on")
myChart

所以如果我尝试

> png(filename="~/Documents/name.png")
> plot(myChart)
Error in as.double(y) : 
  cannot coerce type 'S4' to vector of type 'double'
> dev.off()

我收到那个错误。

我调查了似乎依赖于 Javascript 和 phantomjsHighcharts documentation, as well as many other potential solutions。如果您的答案依赖于 phantomjs,请假设我不知道如何使用它。 webshot 是我发现的另一个包,它甚至包含一个 install_phantomjs() 函数,但据我所知,它要求您先将输出转换为 Shiny 对象。

我的问题实际上是 this one, which is not a duplicate of 的重复,因为那是如何在 Rmarkdown 中嵌入 html 输出,而不是将其作为文件保存在硬盘上。

我也找到了this unanswered question也基本一样

编辑:正如@hrbrmstr 和其他许多人所指出的,雷达图并不总是最好的可视化工具。我发现自己需要为这份报告做一份。

答案竟然在webshot包里。 @hrbrmstr 提供了以下代码,我在问题中发布的代码末尾是 运行:

# If necessary
install.packages("webshot")
library(webshot)
install_phantomjs()

# Main code
myChart$save("/tmp/rcharts.html")
webshot::webshot("/tmp/rcharts.html", file="/tmp/out.png", delay=2)

这会将绘图作为 html 保存到文件夹中,然后拍摄一张照片,将其保存为 png

然后我可以 运行 使用 addImage(mydoc, "/tmp/out.png")ReporteRs 工作流程。