2

When visualizing data with plotly, i want to write widgets as html-documents without htmlwidgets::saveWidget writing dependencies every time, assuming that these already are in place, to save processing time. The widgets need to be self-contained to save disk space.

library(plotly)
t <- Sys.time()
p <- plot_ly(ggplot2::diamonds, y = ~price, color = ~cut, type = "box")
htmlwidgets::saveWidget(as_widget(p), "test.html", selfcontained = F, libdir = NULL)
print(Sys.time() - t)

Time difference of 4.303076 secs on my machine.

This produces ~6 mb of data only in depedencies (crosstalk-1.0.0, htmlwidgets-1.2, jquery-1.11.3, plotly-binding-4.7.1.9000, plotly-htmlwidgets-css-1.38.3, plotly-main-1.38.3, typedarray-0.1)

htmlwidgets::saveWidget writes dependencies although these files already exist. Can this be prevented?

SirSaleh
  • 1,452
  • 3
  • 23
  • 39
Comfort Eagle
  • 2,112
  • 2
  • 22
  • 44

1 Answers1

1

Good question. I tried to answer inline in comments within the code. htmlwidgets dependencies come from two sources: htmlwidgets::getDependency() and the dependencies element in the widget list. Changing the src element within dependencies to href instead of file means these dependencies will not get copied. However, the dependencies from htmlwidgets::getDependency() are harder to overwrite, but in the case will only copy htmlwidgets.js and plotly-binding.js, which are fairly small in comparison with the other four.

library(plotly)

p <- plot_ly(ggplot2::diamonds, y = ~price, color = ~cut, type = "box")

# let's inspect our p htmlwidget list for clues
p$dependencies

# if the src argument for htmltools::htmlDependency
#   is file then the file will be copied
#   but if it is href then the file will not be copied

# start by making a copy of your htmlwidget
#   this is not necessary but we'll do to demonstrate the difference
p2 <- p

p2$dependencies <- lapply(
  p$dependencies,
  function(dep) {
    # I use "" below but guessing that is not really the location
    dep$src$href = "" # directory of your already saved dependency
    dep$src$file = NULL
    
    return(dep)
  }
)

# note this will still copy htmlwidgets and plotly-binding
#  requires a much bigger hack to htmlwidgets::getDependency() to change

t <- Sys.time()
htmlwidgets::saveWidget(as_widget(p), "test.html", selfcontained = F, libdir = NULL)
print(Sys.time() - t)

t <- Sys.time()
htmlwidgets::saveWidget(as_widget(p2), "test.html", selfcontained = F, libdir = NULL)
print(Sys.time() - t)
Vasily A
  • 8,256
  • 10
  • 42
  • 76
timelyportfolio
  • 6,479
  • 30
  • 33