HTML Widgets

Yihui Xie

January 21, 2015 @ LA R Users Group

HTML

HTML body italic

JavaScript

R Markdown

Using JavaScript libraries in R [Markdown/Shiny]

Some may be curious enough to try

Some may quietly give up

Some may lose patience

htmlwidgets: being awesome with low cost

For developers

Installation:

# from CRAN
install.packages("htmlwidgets")
# or development version from Github
devtools::install_github("ramnathv/htmlwidgets")

Documentation: http://htmlwidgets.org

For users

Just install the widget packages, e.g.

# time series charting
devtools::install_github("rstudio/dygraphs")
# DataTables
devtools::install_github("rstudio/DT")
# Leaflet maps
devtools::install_github("rstudio/leaflet")
# network graphs by D3
install.packages("networkD3")
# 3D scatterplots and globe (three.js)
devtools::install_github("bwlewis/rthreejs")
# D3 scatterplots, lines, and bars (MetricsGraphics.js)
devtools::install_github("hrbrmstr/metricsgraphics")

Usage

Demo: dygraphs

library(dygraphs)
dygraph(sunspots) %>% dyRangeSelector()

lungDeaths <- cbind(mdeaths, fdeaths)
dygraph(lungDeaths)

Demo: DataTables

# Pro-tip: R is not SAS
library(DT)
datatable(iris)

m = cbind(matrix(rnorm(60, 1e+05, 1e+06), 20), runif(20), rnorm(20, 100))
m[, 1:3] = round(m[, 1:3])
m[, 4:5] = round(m[, 4:5], 7)
colnames(m) = head(LETTERS, ncol(m))
datatable(m) %>% formatCurrency(c("A", "C")) %>% formatCurrency("B", "€") %>% 
    formatPercentage("D", 2) %>% formatRound("E", 3)

Demo: network graphs

library(networkD3)
data(MisLinks, MisNodes)
str(MisLinks)
## 'data.frame':    254 obs. of  3 variables:
##  $ source: int  1 2 3 3 4 5 6 7 8 9 ...
##  $ target: int  0 0 0 2 0 0 0 0 0 0 ...
##  $ value : int  1 8 10 6 1 1 1 1 2 1 ...
str(MisNodes)
## 'data.frame':    77 obs. of  2 variables:
##  $ name : Factor w/ 77 levels "Anzelma","Babet",..: 63 64 51 57 21 33 12 23 20 65 ...
##  $ group: int  1 1 1 1 1 1 1 1 1 1 ...
forceNetwork(Links = MisLinks, Nodes = MisNodes, Source = "source", Target = "target", 
    Value = "value", NodeID = "name", Group = "group", opacity = 0.4)

Demo: threejs

library(threejs)
data(world.cities, package = "maps")
cities <- world.cities[order(world.cities$pop, decreasing = TRUE)[1:1000], ]
value <- 100 * cities$pop/max(cities$pop)

earth <- texture(system.file("images/world.jpg", package = "threejs"))
globejs(img = earth, lat = cities$lat, long = cities$long, value = value)

Demo: Leaflet maps

library(leaflet)
m <- leaflet() %>% addTiles()
m

m %>% addCircleMarkers(lng = rnorm(100), lat = rnorm(100), radius = runif(100, 
    1, 10))

m %>% addMarkers(-87.9034077, 41.9728589, icon = JS("L.icon({\n    iconUrl: 'https://i.imgur.com/zq3z3e3.png',\n    iconSize: [80, 40]\n  })"))

library(maps)
mapStates <- map("state", fill = TRUE, plot = FALSE)
leaflet(data = mapStates) %>% addTiles() %>% addPolygons(fillColor = topo.colors(10, 
    alpha = NULL), stroke = FALSE)

R graphics vs JS visualizations

Thanks!