使用 htmlwidget 将交互式绘图保存到路径

saving interactive plotly graph to a path using htmlwidget

我正在尝试将一些交互式图形保存到额外的文件中。这适用于 htmlwidget::saveWidget。但是我将它们保存到不同的文件夹中时遇到了问题,例如保存到结果文件夹中。

results_dir <- 'results'
if(!dir.exists(results_dir)) dir.create(results_dir)
p <- plotly::plot_ly(economics, x = ~date, y = ~pop, 
             type = 'scatter', mode = 'markers')
htmlwidgets::saveWidget(p, 
                        file.path(results_dir, 'VSGs.html'))

错误信息是:

Error in normalizePath(basepath, "/", TRUE) :
path[1]="results": No such file or directory

有人知道发生了什么事吗?

我知道之后只需移动文件,但我希望解决此错误消息。

htmlwidgets::saveWidget(p, 'VSGs.html')
file.rename('VSGs.html', file.path(results_dir, 'VSGs.html'))

"results" 似乎不是有效路径
尝试为存在的文件夹设置完整路径。
这应该有效:

dir.create(paste0(getwd(),"/results"))
results_dir = paste0(getwd(),"/results") # get directory

然后用results_dir作为保存路径

中讨论了潜在问题和解决方法

TL/DR: 使用下面的

saveWidgetFix <- function (widget,file,...) {
  ## A wrapper to saveWidget which compensates for arguable BUG in
  ## saveWidget which requires `file` to be in current working
  ## directory.
  wd<-getwd()
  on.exit(setwd(wd))
  outDir<-dirname(file)
  file<-basename(file)
  setwd(outDir);
  saveWidget(widget,file=file,...)
}