A. Welle
A. Welle

Reputation: 21

Using R and plot.ly, how to save multiples htmlwidgets to my html?

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.

A simple example:

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

How can I parse multiple ggplotly objects to saveWidgets?

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

Upvotes: 2

Views: 3790

Answers (2)

timelyportfolio
timelyportfolio

Reputation: 6579

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

Upvotes: 4

steveorsomething
steveorsomething

Reputation: 81

What is the use-case you're after? You may want to consider adding these graphs to a Flexdashboard (which is created in R Markdown). It's been my recent goto, combined with Plotly.

Upvotes: 1

Related Questions