【问题标题】:How to skip writing dependencies in htmlwidgets::saveWidget()?如何跳过在 htmlwidgets::saveWidget() 中编写依赖项?
【发布时间】:2018-07-06 15:20:41
【问题描述】:

当使用 plotly 可视化数据时,我想将小部件编写为 html 文档,而不需要 htmlwidgets::saveWidget 每次都编写依赖项,假设这些已经到位,以节省处理时间。小部件需要自包含以节省磁盘空间。

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 在我的机器上。

这仅在依赖项中产生约 6 mb 的数据(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 写入依赖项,尽管这些文件已经存在。可以预防吗?

【问题讨论】:

    标签: r htmlwidgets r-plotly


    【解决方案1】:

    好问题。我试图在代码中的 cmets 中内联回答。 htmlwidgets 依赖来自两个来源:htmlwidgets::getDependency() 和小部件列表中的 dependencies 元素。将dependencies 中的src 元素更改为href 而不是file 意味着这些依赖项将不会被复制。但是,htmlwidgets::getDependency() 的依赖更难覆盖,但在这种情况下只会复制htmlwidgets.jsplotly-binding.js,与其他四个相比,它们相当小。

    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)
    

    【讨论】:

      猜你喜欢
      • 2022-11-23
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 2013-06-20
      • 2018-01-29
      • 2018-06-03
      • 2017-09-06
      • 2021-05-14
      相关资源
      最近更新 更多