使用R和plot.ly,如何将多个htmlwidget保存到我的html中? [英] Using R and plot.ly, how to save multiples htmlwidgets to my html?

查看:83
本文介绍了使用R和plot.ly,如何将多个htmlwidget保存到我的html中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始在R中使用plot.ly,我对使用htmlwidgets直接在html中发布图形的可能性感到惊讶.到目前为止,我无法在同一HTML中保存多个小部件.我已经在独立的html中保存了多个小部件,然后将它们手动组合到html代码中,但是我希望能够在R中做到这一点.

I´m starting to play with plot.ly in R and I´m amazed with the possibilities to publish my graphs directly in html using htmlwidgets. Until now I´m unable to save multiple widgets in the same html. I have saved multiple widgets in stand-alone htmls and than combine it by hand in the html code, but I would like to be able to do it in R.

一个简单的例子:

#graph
graph<- ggplot(df, aes(x = Data, y=tax))+ geom_bar(stat='identity')
gg <- ggplotly(graph)

# save as HtmlWigdet
htmlwidgets::saveWidget(as.widget(gg), "Index.html")

如何解析多个ggplotly对象以保存小部件?

How can I parse multiple ggplotly objects to saveWidgets?

(这是我在stackoverflow中的第一个问题,希望我做对了!!)

(This is my first question here in stackoverflow, hope I did it right! Regards!)

推荐答案

这是我根据 htmltools 包的各个部分改编而成的功能,用于保存标签列表,然后返回iframe 代码.您可以使用 htmltools :: tagList 包装多个 htmlwidgets ,然后使用此功能保存全部内容.

This is the function I adapted from bits and pieces of the htmltools package to save a tag list and then return an iframe tag. You can wrap multiple htmlwidgets with htmltools::tagList, and then use this function to save the whole bunch.

save_tags <- function (tags, file, selfcontained = F, libdir = "./lib") 
{
  if (is.null(libdir)) {
    libdir <- paste(tools::file_path_sans_ext(basename(file)), 
                    "_files", sep = "")
  }
  htmltools::save_html(tags, file = file, libdir = libdir)
  if (selfcontained) {
    if (!htmlwidgets:::pandoc_available()) {
      stop("Saving a widget with selfcontained = TRUE requires pandoc. For details see:\n", 
           "https://github.com/rstudio/rmarkdown/blob/master/PANDOC.md")
    }
    htmlwidgets:::pandoc_self_contained_html(file, file)
    unlink(libdir, recursive = TRUE)
  }
  return(htmltools::tags$iframe(src= file, height = "400px", width = "100%", style="border:0;"))
}

这篇关于使用R和plot.ly,如何将多个htmlwidget保存到我的html中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆