htmlWidgets Notes

From R Data Visualization by Brooke Anderson on Coursera

Packages

library(leaflet)
library(dygraphs)
library(plotly)
library(rbokeh)
library(networkD3)
library(d3heatmap)
library(DT)
library(DiagrammeR)

##needed for the examples
library(faraway)
library(magrittr)
library(ggplot2)
library(dplyr)
library(tidyr)
library(tigris)
library(viridis)
library(readr)

plotly package

There are two main ways of creating plots using the R plotly package:

  1. Use one of the package’s functions to create a customized interactive graphic:

    *  plot_ly: Workhorse of plotly, renders most non-map types of graphs
    
    *  plot_geo, plot_mapbax: Specific functions for creating plotly maps
  2. Create a ggplot object and then convert it to a plotly object using the ggplotly function.

data(worldcup)
plot_ly(worldcup, type = "scatter",
        x = ~ Time, y = ~ Shots, color = ~ Position)

To show each players name instead of the data points interactivly:

worldcup %>%
  mutate(Name = rownames(worldcup)) %>%
  plot_ly(x = ~ Time, y = ~ Shots, color = ~ Position) %>%
  add_markers(text = ~ Name, hoverinfo = "text")

Or make a custom hover over label with paste

worldcup %>%
  mutate(Name = rownames(worldcup)) %>%
  plot_ly(x = ~ Time, y = ~ Shots, color = ~ Position) %>%
  add_markers(text = ~ paste("<b>Name:</b> ", Name, "<br />", 
                             "<b>Team:</b> ", Team),
              hoverinfo = "text")

Link to html cheat sheet http://web.stanford.edu/group/csp/cs21/htmlcheatsheet.pdf

You can pipe into plot_ly and use add_* which are:

  • add_markers

  • add_lines

  • add_paths

  • add_polygons

  • add_segments

  • add_histogram

pipe to the rangeslider function

read_csv("data/floyd_track.csv") %>%
  plot_ly(x = ~ datetime, y = ~ max_wind) %>% 
  add_lines() %>%
  rangeslider()

3-D Scatter plot!

worldcup %>%
  plot_ly(x = ~ Time, y = ~ Shots, z = ~ Passes,
          color = ~ Position, size = I(3)) %>%
  add_markers()

3-D surface plot!

plot_ly(z = ~ volcano, type = "surface")

Turning ggplot2 plot into plotly

worldcup_scatter <- worldcup %>%
  ggplot(aes(x = Time, y = Shots, color = Position)) + 
  geom_point() 
ggplotly(worldcup_scatter)

Leaflet Interactive Maps

denver_tracts <- tracts(state = "CO", county = 31, cb = TRUE)
load("./data/fars_colorado.RData")
denver_fars <- driver_data %>% 
  filter(county == 31 & longitud < -104.5)
leaflet() %>%
  addTiles() %>%
  addMarkers(data = denver_fars, lng = ~ longitud, lat = ~ latitude)

circles instead of pins

leaflet() %>%
  addTiles() %>%
  addCircleMarkers(data = denver_fars, radius = 2,
                   lng = ~ longitud, lat = ~ latitude)

clustering instead of too many pins

leaflet() %>%
  addTiles() %>%
  addMarkers(data = denver_fars, 
                   lng = ~ longitud, lat = ~ latitude,
                   clusterOptions = markerClusterOptions())

the tiles default to open street map but you can see more options here: http://leaflet-extras.github.io/leaflet-providers/preview/index.html here’s a watercolor tile set

leaflet() %>%
  addProviderTiles("Stamen.Watercolor") %>%
  addCircleMarkers(data = denver_fars, radius = 2,
                   lng = ~ longitud, lat = ~ latitude)

Popups

leaflet() %>%
  addTiles() %>%
  addCircleMarkers(data = denver_fars, radius = 2, 
                   lng = ~ longitud, lat = ~ latitude,
                   popup = ~ paste("<b>Driver age:</b>", age))

Complex popups from an added table

denver_fars <- denver_fars %>%
  mutate(popup_info = paste("<b>Driver age:</b>", age, "<br />",
                            "<b>Date:</b>", format(date, "%Y-%m-%d"), "<br />",
                            "<b>Time:</b>", format(date, "%H:%M"), "<br />"),
         popup_info = ifelse(!is.na(alc_res),
                             paste(popup_info,
                                   "<b>Blood alcohol</b>", alc_res, "<br />"),
                             popup_info)) 

denver_fars %>%
  leaflet() %>%
  addTiles() %>%
  addCircleMarkers(radius = 2, lng = ~ longitud, lat = ~ latitude,
                   popup = ~ popup_info)

Using color to show the number of drunk drivers

pal <- colorFactor(viridis(5), denver_fars$drunk_dr)
leaflet() %>%
  addProviderTiles("OpenStreetMap.BlackAndWhite") %>%
  addCircleMarkers(data = denver_fars, radius = 2,
                   lng = ~ longitud, lat = ~ latitude,
                   popup = ~ popup_info,
                   color = ~ pal(drunk_dr)) 

Add a legend

pal <- colorFactor(viridis(5), denver_fars$drunk_dr)
leaflet() %>%
  addProviderTiles("OpenStreetMap.BlackAndWhite") %>%
  addCircleMarkers(data = denver_fars, radius = 2,
                   lng = ~ longitud, lat = ~ latitude,
                   popup = ~ popup_info,
                   color = ~ pal(drunk_dr)) %>%
  addLegend(pal = pal, values = denver_fars$drunk_dr)

Add polygons

leaflet() %>%
  addProviderTiles("OpenStreetMap.BlackAndWhite") %>%
  addPolygons(data = denver_tracts)

Popups for polygons

leaflet() %>%
  addProviderTiles("OpenStreetMap.BlackAndWhite") %>%
  addPolygons(data = denver_tracts, 
              popup = paste0("Tract ID:  ", denver_tracts@data$NAME))

Multiple elements

leaflet() %>%
  addProviderTiles("OpenStreetMap.BlackAndWhite") %>%
  addPolygons(data = denver_tracts,
              popup = paste0("Tract ID:  ", denver_tracts@data$NAME),
              color = "#000000", fillColor = "969696", 
              weight = 2) %>%
  addCircleMarkers(data = denver_fars, lat = ~ latitude, 
                   lng = ~ longitud, radius = 2,
                   popup = ~ popup_info, opacity = 0.9,
                   color = ~ pal(drunk_dr)) %>%
  addLegend(pal = pal, values = denver_fars$drunk_dr, opacity = 0.9)

Adding layer control

leaflet() %>%
  addProviderTiles("OpenStreetMap.BlackAndWhite") %>%
  addPolygons(data = denver_tracts,
              popup = paste0("Tract ID:  ", denver_tracts@data$NAME),
              color = "#000000", fillColor = "969696", 
              weight = 2, group = "tracts") %>%
  addCircleMarkers(data = denver_fars, lat = ~ latitude, 
                   lng = ~ longitud, radius = 2,
                   popup = ~ popup_info, opacity = 0.9,
                   color = ~ pal(drunk_dr),
                   group = "accidents") %>%
  addLegend(pal = pal, values = denver_fars$drunk_dr, opacity = 0.9) %>%
  addLayersControl(baseGroups = c("base map"), 
                   overlayGroups = c("tracts", "accidents"))