Last active
          June 7, 2020 04:46 
        
      - 
      
- 
        Save burchill/9df0f6245ea7768e5b6bbd0a1c22db08 to your computer and use it in GitHub Desktop. 
    Enable Plotly plots in knitr-powered Jekyll
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | plotly_manager <- function( | |
| postdir = knitr::opts_chunk$get("plotly.savepath"), # I have this as a default knitr option. Either change or specify your own when you call it | |
| basedir = knitr::opts_chunk$get("proj.basedir"), # Ditto. See: https://www.zachburchill.ml/plotly_with_jekyll/ for explanation | |
| libdirname = "js_files/", | |
| hrefFilter = function(x) paste0("/", x)) { | |
| deps <- list() | |
| libdir <- paste0(postdir, libdirname) | |
| render_deps <- function(l) { | |
| if (length(l) > 0) | |
| dir.create(libdir, showWarnings = FALSE, recursive = TRUE) | |
| l <- lapply(unique(l), function(dep) { | |
| dep <- htmltools::copyDependencyToDir(dep, libdir, FALSE) | |
| dep <- htmltools::makeDependencyRelative(dep, basedir, FALSE) | |
| dep } ) | |
| l <- htmltools::renderDependencies(l, hrefFilter=hrefFilter) | |
| htmltools::htmlPreserve(l) | |
| } | |
| add_deps_from_plot <- function(p) { | |
| deps <<- append(deps, htmltools::renderTags(p)$dependencies) | |
| } | |
| plot_plotly <- function(p) { | |
| add_deps_from_plot(p) | |
| htmltools::tagList(list(plotly::as_widget(p))) | |
| } | |
| prev_doc_hook <- knitr::knit_hooks$get("document") | |
| knitr::knit_hooks$set(document = function(x) { | |
| prev_doc_hook(append(x, render_deps(deps))) | |
| }) | |
| plot_plotly | |
| } | |
| # # Use it like: | |
| # ```{r} | |
| # plot_plotly <- plotly_manager() | |
| # p <- ggplot2::qplot(x=1,y=1) | |
| # p <- plotly::ggplotly(p) | |
| # ``` | |
| # # And then: | |
| # ```{r} | |
| # plot_plotly(p) | |
| # ``` | |
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment