【问题标题】:force Rscript to open plotly in browser viewer强制Rscript在浏览器查看器中打开
【发布时间】:2018-03-07 11:07:43
【问题描述】:

我在plot.R 文件中有以下代码。

library(plotly)
options(browser = "/opt/google/chrome/chrome")
options(viewer = NULL)

plot_ly(economics, x = ~date, y = ~pce, z = ~pop) %>%
  htmlwidgets::onRender(
    "function(el, x) {
     var gd = document.getElementById(el.id); 
     Plotly.downloadImage(gd, {format: 'png', width: 600, height: 400, filename: 'plot'});
   }"
  )

从 Rstudio 或 R 控制台运行此代码按预期工作:svg 图像保存在 chrome 中指定的下载目录中。然而,来自 RStudio 的source('plot.R') 或来自控制台的Rscript plot.R 似乎都没有打开浏览器并保存图像。没有错误。

我需要能够使用Rscript 命令运行此脚本。

更新

感谢 Krystian 回答添加 print() 对 Rstudio 的帮助。但是,我仍然无法让浏览器查看器打开 frm RScript。

【问题讨论】:

    标签: r htmlwidgets


    【解决方案1】:

    只需在创建的情节上强制使用print 方法:

    plot_ly(economics, x = ~date, y = ~pce, z = ~pop) %>%
      htmlwidgets::onRender(
        "function(el, x) {
         var gd = document.getElementById(el.id); 
         Plotly.downloadImage(gd, {format: 'png', width: 600, height: 400, filename: 'plot'});
       }"
      ) %>% print
    

    【讨论】:

    • 感谢这在 RStudio 中有效,但不幸的是Rscript plot.R
    【解决方案2】:

    如果您有兴趣保存图像而不是浏览器打开,以下脚本可以帮助您:https://gist.github.com/anadiedrichs/68dbadd4135acc9a51ff8520a5cd987c

    该示例使用 webshot 库来满足您的需要。

    1. 您必须安装 plotly、webshot 和 htmltools 包
    2. 运行:webshot::install_phantomjs()
    3. 根据自己的需要使用/修改以下脚本。

    【讨论】:

      猜你喜欢
      • 2012-08-17
      • 2012-09-29
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      相关资源
      最近更新 更多