Embedding an R htmlwidget into existing webpage

前端 未结 1 469
一向
一向 2020-12-08 07:33

I am trying to embed an R htmlwidget into an existing webpage -- a webpage that already has bootstrap and styling applied. For example, consider the following w

1条回答
  •  长情又很酷
    2020-12-08 08:25

    The htmlwidget-Package offers a way to save the pieces for the widget separately as follows:

    library(dygraphs)
    d1 <- dygraph(nhtemp, main = "New Haven Temperatures") %>% 
      dyRangeSelector(dateWindow = c("1920-01-01", "1960-01-01"))
    
    saveWidget(d1, file = "widget_file.html", selfcontained = FALSE)
    

    Which results in the following files/dirs:

    widget_file.html
    widget_file_files
      /dygraphs-1.1.1
        ..
      /dygraphs-binding-0.6
        ..
      /htmlwidgets-0.5
        ..
      /jquery-1.11.1
        ..
      /moment-2.8.4  
        ..
      /moment-timezone-0.2.5
        ..
    

    And widget_file.html reads as follows:

    
    
    
    
    
    ...
    
    
    
    
    

    So you can edit your html as follows:

    
    
    
      
      Document
      
      
      
      
      
      
      
      
      
    
      
        
      
    
      
      
      
    
    
      

    This is a test.

    A closing paragraph.

    This will leave you with the json-data hardcoded within the html-document (see my ). If you want to load the data dynamically you can use e.g.

    json_dat <- readLines("widget_file.html")[18]
    cat(sub("","",sub('
    

    If you want to use a pure JS solution maybe have a look at http://api.jquery.com/jquery.getjson/ and the widget_file_files/htmlwidgets-0.5/htmlwidgets.js-File how the json-data is bound at the moment...

    P.S.: As this question got a lot of attention already you could also contact the package developer and ask him to further "un-selfcontain" the "selfcontained" option in htmlwidgets:::saveWidget: Meaning to save the json-data separately and include it e.g. via jquery.getjson

    0 讨论(0)
提交回复
热议问题