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



我想用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)

生成此图后,当我单击R-Studio的Plot窗口中的"Export"按钮时,我可以选择将绘图保存为网页。如何编写将生成的绘图保存为网页的过程脚本?我的最终目标是从bash脚本内部迭代运行Rscripts,以生成多个网页。

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")

更新Andrew对R-3.5.1和图4.8.0的回答,即:

library(plotly)
set.seed(100)
d <- diamonds[sample(nrow(diamonds), 1000), ]
p <- plot_ly(d, x = ~carat, y = ~price, text=~paste("Clarity : ", clarity))
htmlwidgets::saveWidget(as_widget(p), "index.html")

为了让它发挥作用,你还需要安装pandoc。在Cents/ReHat上执行yum install pandoc pandoc-citeproc。在Mac OSX上,使用自制程序,执行brew install pandoc

该解决方案已在OSX 10.13.6上进行了测试,并在R-3.5.1中运行。

最新更新