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 and writes out files to DBFS’s FileStore without cleaning up after itself.
The new method avoids those steps and is drastically simplified and easier to use, just run the below function in a Databricks notebook:
enable_htmlwidgets <-function(height =450) {# new option to control default widget height, default is 450px1options(db_htmlwidget_height = height)2system("apt-get update && apt-get --yes install pandoc", intern = T)3if (!base::require("htmlwidgets")) { utils::install.packages("htmlwidgets") }# new method will fetch height based on new option, or default to 450px4 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