使用R和plot.ly - 如何将输出脚本保存为网页

Sla*_*ron 21 r plotly

我想用R和plot.ly制作一些交互式图形.当我在R-Studio中运行以下代码时,它会生成一个交互式图形.

library(plotly)
set.seed(100)
d <- diamonds[sample(nrow(diamonds), 1000), ]
plot_ly(d, x = carat, y = price, text = paste("Clarity: ", clarity),
    mode = "markers", color = carat, size = carat)
Run Code Online (Sandbox Code Playgroud)

生成此图形后,当我单击R-Studio的"绘图"窗口中的"导出"按钮时,它为我提供了将绘图保存为网页的选项.如何编写将生成的图表保存为网页的过程?我的最终目标是从bash脚本中迭代运行Rscripts以生成多个网页.

And*_*rew 46

将plot_ly对象分配给变量,然后使用htmlwidgets::saveWidget()保存实际文件,如下所示:

library(plotly)
set.seed(100)
d <- diamonds[sample(nrow(diamonds), 1000), ]
p <- plot_ly(d, x = carat, y = price, text = paste("Clarity: ", clarity),
             mode = "markers", color = carat, size = carat)
htmlwidgets::saveWidget(as_widget(p), "index.html")
Run Code Online (Sandbox Code Playgroud)

  • `as.widget` 是 [plotly 的一部分](https://github.com/ropensci/plotly/blob/d16be22f284ad36fba3c14f2b3cc015064e74cf3/man/as.widget.Rd),但它是在 12 月底才添加的,所以你可能正在运行旧版本的库。 (2认同)
  • CRAN版本的情节是2.0.16并且建于12月20日.在12月23日添加了as.widget`,所以它还没有在CRAN上.使用devtools从GitHub安装开发版本:`devtools :: install_github("ropensci/plotly")`它应该可以工作. (2认同)
  • 该函数默认将其保存到工作目录。不过,您可以选择您想要的任何路径: `htmlwidgets::saveWidget(as.widget(p), "/path/to/wherever/blah.html")` (2认同)