htmlwidgets-azure(R)
Loading...

HTML Widgets in Azure Databricks R Notebooks

This example notebook shows how you can get R HTML widgets working in Azure Databricks notebooks. The setup has two steps:

  1. Installing pandoc, a Linux package that is used by HTML widgets to generate HTML
  2. Changing one function within HTML Widgets package to make it seemless work in Azure Databricks. Make sure you use correct URL of your Azure Databricks environment.

Both steps can be automated using init scripts so that when your cluster launches it installs pandoc and updates R HTMLwidgets package automatically.

This notebook shows three examples using HTMLWidgets: dygraphs, leaflet, and plotly

%sh apt-get --yes install pandoc
require(devtools)
install_version("htmltools", version = "0.4.0", repos = "http://cran.us.r-project.org")
library(htmltools)
install.packages("htmlwidgets")
library(htmlwidgets)
## Replace <region> with the region of your Azure Databricks Account URL
## Make sure you use HTTPS
databricksURL <- "https://<region>.azuredatabricks.net/files/rwidgets/"
## Replace <workspace-id> with the workspace ID of your Azure Databricks Account URL
db_html_print <- function(x, ..., view = interactive()) {
  fileName <- paste(tempfile(), ".html", sep="")
  htmlwidgets::saveWidget(x, file = fileName)
  
  randomFileName = paste0(floor(runif(1, 0, 10^12)), ".html")
  baseDir <- "/dbfs/FileStore/rwidgets/"
  dir.create(baseDir)
  internalFile = paste0(baseDir, randomFileName)
  externalFile = paste0(databricksURL, randomFileName, "?o=<workspace-id>")
  system(paste("cp", fileName, internalFile))
  displayHTML(externalFile)
}
R.utils::reassignInPackage("print.htmlwidget", pkgName = "htmlwidgets", value = db_html_print)

Example HTML widget with dygraphs

install.packages("dygraphs")
library(dygraphs)
dygraph(cbind(mdeaths, fdeaths))

Example with leaflet

install.packages("leaflet")
library(leaflet)
library(magrittr)

leaflet() %>%
  addTiles() %>% 
  addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")

Example with plotly

install.packages("plotly")
library(plotly)
p <- plot_ly(midwest, x = ~percollege, color = ~state, type = "box")
p