7  {htmlwidgets} in notebooks

When you try to view a {htmlwidget} based visualisation (e.g. {leaflet}) in a Databricks notebook you’ll find there is no rendered output by default.

The Databricks documentation details how to get this working but requires specification of the workspace URL explicitly.

{brickster} has a helper function that simplifies enabling {htmlwidgets}:

remotes::install_github("zacdav-db/brickster")
brickster::notebook_enable_htmlwidgets()

The function itself is straightforward, here is code (simplified version of brickster::notebook_enable_htmlwidgets) that doesn’t require installing {brickster}:

enable_htmlwidgets <- function(height = 450) {

  # new option to control default widget height, default is 450px
1  options(db_htmlwidget_height = height)

2  system("apt-get --yes install pandoc", intern = T)
3  if (!base::require("htmlwidgets")) {
    utils::install.packages("htmlwidgets")
  }

  # new method will fetch height based on new option, or default to 450px
4  new_method <- function(x, ...) {
    x$height <- getOption("db_htmlwidget_height", 450)
    file <- tempfile(fileext = ".html")
    htmlwidgets::saveWidget(x, file = file)
    contents <- as.character(rvest::read_html(file))
    displayHTML(contents)
  }

5  utils::assignInNamespace("print.htmlwidget", new_method, ns = "htmlwidgets")
  invisible(list(default_height = height, print = new_method))
  
}
1
The height of the htmlwidget output is controlled via an option (db_htmlwidget_height), this allows the height to be adjusted without re-running the function
2
Installing pandoc as it’s required to use htmlwidgets::saveWidget
3
Ensure that {htmlwidgets} is installed
4
Function that writes the widget to a temporary file as a self-contained html file and then reads the contents and presents via displayHTML
5
Override the htmlwidgets::print.htmlwidget method