27 min read

Insert HTML Widgets in Blogdown


leaflet map of Evansville
An embedded leaflet map of downtown Evansville.

View raw source for this post

Summary

Blogdown & Hugo allow for the insertion of html widgets like leaflet. This is a huge time saver because one doesn’t need to learn java and can instead stay within the R environment.

Table of Contents

Why Blogdown?

There were two main reasons for moving to blogdown. First, I needed a blogging platform that moved seemlessly between R code and its output. It had to be easy to show the connection between the code that was used and its effect on the data. Put the two side-by-side and people can understand what happened. It’s how I learn off the console.

The second reason was that blogdown offered the promise of embedding html widgets into a post. The htmlwidgets package is so important in that it prevents me from having to learn java. Don’t get me wrong, java is important, but I can barely get around in R and want to stay focused on working with data, not learning new computer languages. This proved to be difficult, because there were no less than four hugo-themes that I tried, but kept having problems with the display in a webpage. It was frustrating to say the least.

Not being able to embed dynamic tables into a website is a dealbreaker for me. Yes, my writing is more dependent, for example, on plots. But a dynamic table in the modern internet world just seems to be a necessity for readers. That’s why I’ve started this article by using the DT package in placing the mtcars dataset into a table. It worked!

Also, find other examples of html embeds below. For more information on the htmlwidgets package, see Rstudio’s page

Load Libraries

my.pkgs <- c("leaflet", "widgetframe", "htmlwidgets",
             "magrittr", "sigma", "DT", "ggplot2", "plotly")
lapply(my.pkgs, function(x) suppressPackageStartupMessages(library(x, character.only = T)))

Insert Data Tables or DT Widget

# see https://rstudio.github.io/DT/
DT::datatable(iris)

Insert Leaflet Widget

# https://bhaskarvk.github.io/widgetframe/
#wrap widget in <iframe> tags
m <- leaflet() %>%
  addTiles() %>%
  fitBounds(0, 40, 10, 50) %>%
  # move the center to Evansville
  setView(-87.569908, 37.975712, zoom = 15)
frameWidget(m)

Insert Sigma JS

data <- system.file("examples/ediaspora.gexf.xml", package = "sigma")
sigma(data)

Insert Plotly Widget

#https://www.htmlwidgets.org/showcase_plotly.html
p <- ggplot(data = diamonds, aes(x = cut, fill = clarity)) +
            geom_bar(position = "dodge")
ggplotly(p)