---
title: "Dynamic Visualization"
---

```{r, echo=FALSE, message=FALSE, results='hide', purl=FALSE}
source("knitr_header.R")
```


[<i class="fa fa-file-code-o fa-3x" aria-hidden="true"></i> The R Script associated with this page is available here](`r output`).  Download this file and open it (or copy-paste into a new script) with RStudio so you can follow along.  

# Introduction

In this module we will explore several ways to generate dynamic and interactive data displays.  These include making maps and graphs that you can pan/zoom, select features for more information, and interact with in other ways.  The most common output format is HTML, which can easily be embedded in a website (such as your final project!).

```{r cache=F, message=F,warning=FALSE}
library(dplyr)
library(ggplot2)
library(ggmap)
library(htmlwidgets)
library(widgetframe)
```

If you don't have the packages above, install them in the package manager or by running `install.packages("doParallel")`. 

# DataTables

[DataTables](http://rstudio.github.io/DT/) display R data frames as interactive HTML tables (with filtering, pagination, sorting, and search).  This is a great way to make your raw data browsable without using too much space.

```{r}
library(DT)
datatable(iris, options = list(pageLength = 5))
```

# rbokeh

Interface to the [Bokeh](http://hafen.github.io/rbokeh) library for making interactive graphics.

```{r, warning=F, message=F}
library(rbokeh)
figure(width = 400, height=400) %>%
  ly_points(Sepal.Length, Sepal.Width, data = iris,
    color = Species, glyph = Species,
    hover = list(Sepal.Length, Sepal.Width))
```


# Leaflet

[Leaflet](http://rstudio.github.io/leaflet/) is a really powerful JavaScript library for creating dynamic maps that support panning and zooming along with various annotations like markers, polygons, and popups.  The example below were adapted from the [leaflet vignettes](http://rstudio.github.io/leaflet).

```{r, warning=F, message=F}
library(leaflet)
geocode("Buffalo, NY")
m <- leaflet() %>% setView(lng = -78.87837, lat = 42.88645, zoom = 12) %>% 
  addTiles()
frameWidget(m,height =500)
```


<div class="well">
## Your turn
This example only scratches the surface of what is possible with leaflet.  Consider whether you can use an leaflet maps in your project.  

* Browse the [Leaflet website](http://rstudio.github.io/leaflet/) 
* What data could you use? 
* How would you display it?
</div>


# dygraphs
An R interface to the 'dygraphs' JavaScript charting library. Provides rich facilities for charting time-series data in R, including highly configurable series- and axis-display and interactive features like zoom/pan and series/point highlighting.
    
```{r, warning=F}
library(dygraphs)
dygraph(nhtemp, main = "New Haven Temperatures",height = 100) %>% 
  dyRangeSelector(dateWindow = c("1920-01-01", "1960-01-01"))%>%
  frameWidget(height =500)

```

<div class="well">
## Your turn
Make a dygraph of recent daily maximum temperature data from Buffalo, NY.

Hints:

* Use the following code to download the daily weather data (if this is taking too long, you can use the nhtemps object loaded above)
```{r, messages=F, warning=F, results=F}
library(rnoaa)
library(xts)

d=meteo_tidy_ghcnd("USW00014733",
                   date_min = "2016-01-01", 
                   var = c("TMAX"),
                   keep_flags=T)
d$date=as.Date(d$date)
```

* create a `xts` time series object as required by `dygraph()` using `xts()` and specify the vector of data and the date column (see `?xts` for help). 
* use `dygraph()` to draw the plot
* add a `dyRangeSelector()` with a `dateWindow` of `c("2017-01-01", "2017-12-31")`

<button data-toggle="collapse" class="btn btn-primary btn-sm round" data-target="#demo2">Show Solution</button>
<div id="demo2" class="collapse">

```{r, purl=F, warning=F, message=F}
# Convert to a xts time series object as required by dygraph
dt=xts(d$tmax,order.by=d$date)

dygraph(dt, main = "Daily Maximum Temperature in Buffalo, NY") %>% 
  dyRangeSelector(dateWindow = c("2017-01-01", "2017-12-31"))%>%
  frameWidget(height =500)
```
</div>
</div>

# rthreejs

Create interactive 3D scatter plots, network plots, and globes using the ['three.js' visualization library](https://threejs.org).
    
```{r, message=F, results=F}
#devtools::install_github("bwlewis/rthreejs")
library(threejs)
z <- seq(-10, 10, 0.1)
x <- cos(z)
y <- sin(z)
scatterplot3js(x, y, z, color=rainbow(length(z)))
```

# networkD3

Creates 'D3' 'JavaScript' network, tree, dendrogram, and Sankey graphs from 'R'.
    
```{r, message=F, results=F}
library(igraph)
library(networkD3)
```


## Load example network
This loads an example social network of friendships between 34 members of a karate club at a US university in the 1970s. See W. W. Zachary, An information flow model for conflict and fission in small groups, Journal of Anthropological Research 33, 452-473 (1977).

```{r}
karate <- make_graph("Zachary")
wc <- cluster_walktrap(karate)
members <- membership(wc)

# Convert to object suitable for networkD3
karate_d3 <- igraph_to_networkD3(karate, group = members)
```

## Force directed network plot

```{r}
forceNetwork(Links = karate_d3$links, Nodes = karate_d3$nodes,
             Source = 'source', Target = 'target', NodeID = 'name',
             Group = 'group')%>%
  frameWidget(height =500)
```


## Sankey Network graph

Sankey diagrams are flow diagrams in which the width of the arrows is shown proportionally to the flow quantity.

```{r}
# Load energy projection data
library(jsonlite)
URL <- paste0(
        "https://cdn.rawgit.com/christophergandrud/networkD3/",
        "master/JSONdata/energy.json")
Energy <- fromJSON(URL)
```

```{r}
sankeyNetwork(Links = Energy$links, Nodes = Energy$nodes, Source = "source",
             Target = "target", Value = "value", NodeID = "name",
             units = "TWh", fontSize = 12, nodeWidth = 30)%>%
  frameWidget(height =500)
```

## Radial Network
```{r}
URL <- paste0(
        "https://cdn.rawgit.com/christophergandrud/networkD3/",
        "master/JSONdata//flare.json")

## Convert to list format
Flare <- jsonlite::fromJSON(URL, simplifyDataFrame = FALSE)
```


```{r}
# Use subset of data for more readable diagram
Flare$children = Flare$children[1:3]

radialNetwork(List = Flare, fontSize = 10, opacity = 0.9, height = 400, width=400)
```

# Diagonal Network
```{r}
diagonalNetwork(List = Flare, fontSize = 10, opacity = 0.9, height = 400, width=400)
```


# rglwidget

RGL provides 3D interactive graphics, including functions modelled on base graphics (`plot3d()`, etc.) as well as functions for constructing representations of geometric objects (`cube3d()`, etc.).  You may need to install [XQuartz](https://www.xquartz.org/).

```{r, message=F}
library(rgl)
library(rglwidget)
library(htmltools)

# Load a low-resolution elevation dataset of a volcano
data(volcano)
```

## Plot an interactive 3D _surface_
```{r}
persp3d(volcano, type="s",col="green3")
rglwidget(elementId = "example", width = 500, height = 400)%>%
  frameWidget()
```


<div class="well">
## Your turn

Check out the [HTML Widgets page](http://gallery.htmlwidgets.org/) for many more examples.

Which can you use in your project?

</div>


