Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Enable Plotly plots in knitr-powered Jekyll
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
You can’t perform that action at this time.