【问题标题】:saving interactive plotly graph to a path using htmlwidget使用 htmlwidget 将交互式绘图保存到路径
【发布时间】:2018-02-08 16:56:15
【问题描述】:

我正在尝试将一些交互式图形保存到额外的文件中。这适用于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'))

错误信息是:

normalizePath 中的错误(基本路径,“/”,TRUE):
path[1]="results": 没有这样的文件或目录

有人知道发生了什么吗?

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

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

【问题讨论】:

    标签: r plotly htmlwidgets


    【解决方案1】:

    “结果”似乎不是有效路径
    尝试设置存在的文件夹的完整路径。
    这应该工作:

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

    然后使用 results_dir 作为保存路径。

    【讨论】:

    • 谢谢,没想到这一点,但是使用全局路径它工作得很好。所以我将保存命令替换为htmlwidgets::saveWidget(p, file.path(getwd(), results_dir, 'VSGs.html'))
    • 我建议设置一个您确定的路径,而不仅仅是工作目录。
    • 要遵循该评论,我的结果目录与我的工作目录相关,这就是为什么我认为这样可以,只有 saveWidget 没有正确执行。对您的代码的另一条评论,最好使用file.path 而不是paste0,因为这也处理了windows 或unix 路径。另外,您在/rsults 中有错字... :-) 不想成为一个聪明人 :-)
    【解决方案2】:

    savewidget from htmlwidget in R , cannot save html file in another folder 中讨论了基本问题并提供了解决方法

    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,...)
    }
    

    【讨论】:

    • 我在 GitHub 上也收到了您的评论。谢谢。我现在更喜欢用file.path(getwd(), 'outdir', 'widget.html') 创建一个绝对路径,而不是创建一个额外的函数。我不想稍后更改我的代码并删除我的函数,以防万一得到修复。
    猜你喜欢
    • 2022-07-06
    • 1970-01-01
    • 2012-11-25
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 2018-10-13
    • 2012-05-12
    相关资源
    最近更新 更多