簡體   English   中英

如何在RStudio中的Viewer中將圖形保存為磁盤上的圖像?

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

簡介:我的最終目標是使用rCharts ,特別是Highcharts ,作為ReporteRs PowerPoint報告自動化工作流程的一部分。 我想使用的其中一個圖表在Rstudio的Viewer窗格中呈現為html,而addPlot(function() print(myChart))不會將其添加到PowerPoint中。 作為一種解決方法,我決定嘗試將myChart保存到磁盤,從那里我可以將其添加到PowerPoint中。

所以我的問題是, 如何將我的html圖像放入ReporteRs工作流程? 要么將其保存到磁盤,要么讓它可由ReporteRs讀取, ReporteRs將解決我的問題。

這個問題確實是一樣的這一個 ,但我使用rCharts ,特別是例如發現這里

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

我收到了這個錯誤。

我已經研究過Highcharts文檔 ,以及許多 其他似乎依賴於Javascript和phantomjs 潛在 解決方案 如果你的答案依賴於phantomjs ,請假設我不知道如何使用它。 webshot是我發現的另一個包,它甚至包括一個install_phantomjs()函數,但是從我能找到的,它要求你先將輸出變成一個Shiny對象。

我的問題是真正的副本這一塊 ,這不是重復這一塊 ,因為這是如何嵌入HTML輸出在Rmarkdown,而不是將其保存為硬盤驅動器上的文件。

我也發現這個未解決的問題也基本相同。

編輯:正如@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工作流程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM