Creating Interactive Visualisation Tools With R

Overview


  • Themes
    • Interactive Data Analysis
    • Exploratory Spatial Data Analysis
    • Time Series
    • Maps with Backdrops

Solution to Self-Test

Create dygraph as follows:

rain %>%  group_by(Year,Month) %>% filter(Station=="Cork Airport") %>%
    summarise(Rainfall=sum(Rainfall)) %>% ungroup %>% transmute(Rainfall) %>%
    ts(start=c(1850,1),freq=12) ->  cork_ts
bdc_ts <- cbind(bel_ts,dub_ts,cork_ts)
bdc_ts %>% dygraph(width=800,height=450) %>% dyRangeSelector %>% dyRoller

Further Interactive Techniques

🔦 Overview


  • More on interaction
  • Interactive maps for temporal exploration

📆 Seasonal Analysis Revisited


  • Firstly sort data by Year then Month.
load('rainfall.RData')
library(dplyr)
rain %>% arrange(Year,Month) -> rain2
head(rain2,n=4) # Note n=4 reduces the number of observations
## # A tibble: 4 x 4
##    Year Month Rainfall Station   
##   <dbl> <fct>    <dbl> <chr>     
## 1  1850 Jan      169   Ardara    
## 2  1850 Jan       96.9 Derry     
## 3  1850 Jan      108.  Malin Head
## 4  1850 Jan       92.5 Armagh
  • Function for creating a monthplot for a given station
local_monthplot <- function(station,raindata) {
  raindata %>% filter(Station == station) -> local_rd
  local_rd$Rainfall %>% ts(freq=12,start=1850) -> rain_ts
  rain_ts %>% monthplot(col='dodgerblue',col.base='indianred',lwd.base=3)
  title(station)
}

Selective monthplots in use:

local_monthplot('Derry',rain2)

💾 Saving an image


png('test.png',width=400,height=300)
local_monthplot('Derry',rain2)
dev.off()

  • No graph appears - but it is stored in test.png
  • Try clicking on it after running the above code
  • Depending on your operating system, an application should open it

A filename for each station


library(leaflet)
library(mapview)
library(leafpop)

stations %>% mutate(Filename=file.path(getwd(),paste0(Station,'.png'))) -> files
files %>% select(Station,Filename) %>% head
## # A tibble: 6 x 2
##   Station     Filename                                                          
##   <chr>       <chr>                                                             
## 1 Athboy      /Users/chrisbrunsdon/Dropbox/climate_change/Time Series etc Modul…
## 2 Foulksmills /Users/chrisbrunsdon/Dropbox/climate_change/Time Series etc Modul…
## 3 Mullingar   /Users/chrisbrunsdon/Dropbox/climate_change/Time Series etc Modul…
## 4 Portlaw     /Users/chrisbrunsdon/Dropbox/climate_change/Time Series etc Modul…
## 5 Rathdrum    /Users/chrisbrunsdon/Dropbox/climate_change/Time Series etc Modul…
## 6 Strokestown /Users/chrisbrunsdon/Dropbox/climate_change/Time Series etc Modul…

  • paste0 joins character variables together
    • Like paste with no spacing
  • select pulls out variables of interest

Embedding Graphics - 1

  • tmap is built on another package called leaflet
  • leaflet is more powerful and fklexible
  • leaflet is generally harder to use
  • You can start off a map object in tmap but switch to leaflet
    1. create a tmap object in 'view' mode
    2. Convert with tmap_leaflet
    3. take it from there…

Embedding Graphics - 2

library(sf)
library(tmap)
counties <- st_read('counties.geojson') %>% st_transform(4326) # leaflet objects must be long/lat (epsg 4326)
tmap_mode('view')
tm_start <- tm_shape(counties) + tm_borders()
tm_start

Embedding Graphics - 3

tmap_leaflet(tm_start) %>% 
  addPolygons(data=counties,
              color = NA,  
              popup = popupImage('test.png',embed = TRUE)) 

A monthplot for each station


for (i in 1:nrow(files))
  with(files, {
    png(Filename[i],width=400,height=300)
    local_monthplot(Station[i],rain2)
    dev.off()} )

  • Check your directory again
    • Should be a png for each Station

Making each monthplot a pop-up


files %>% mutate(Popup=paste0('<img src="',Filename,'">')) -> files
files %>% select(Station,Popup) %>% head
## # A tibble: 6 x 2
##   Station     Popup                                                             
##   <chr>       <chr>                                                             
## 1 Athboy      "<img src=\"/Users/chrisbrunsdon/Dropbox/climate_change/Time Seri…
## 2 Foulksmills "<img src=\"/Users/chrisbrunsdon/Dropbox/climate_change/Time Seri…
## 3 Mullingar   "<img src=\"/Users/chrisbrunsdon/Dropbox/climate_change/Time Seri…
## 4 Portlaw     "<img src=\"/Users/chrisbrunsdon/Dropbox/climate_change/Time Seri…
## 5 Rathdrum    "<img src=\"/Users/chrisbrunsdon/Dropbox/climate_change/Time Seri…
## 6 Strokestown "<img src=\"/Users/chrisbrunsdon/Dropbox/climate_change/Time Seri…

  • Note combined use of " and '
    • You can enclose ' in a string delimited by "
    • and vice versa
    • This has created the popup control strings

Putting it together (1) …


tmap_leaflet(tm_start) %>% 
  addCircleMarkers(data=station_means,
                   popup=popupImage(station_means$Filename,embed=TRUE)) 

Putting it together (2) …


tm_start2 <- tm_shape(station_means) + tm_dots(col='mrain',popup.vars=FALSE,scale=1.5)
tmap_leaflet(tm_start2) %>% 
  addCircleMarkers(data=station_means,stroke = NA,
                   popup=popupImage(station_means$Filename,embed=TRUE)) 

Notes

  • tm_start2 is a new tmap kick-off map based on shading the dots by mean rainfall.
  • popup_vars = FALSE stops pop-up on tmap map
    • gets confusing if both leaflet and tmap have pop-ups
  • stroke=NA stops leaflet drawing an outer ring on the pop-up markers

More leaflet - Scale bars

tmap_leaflet(tm_start2) %>% 
  addCircleMarkers(data=station_means,stroke = NA,
                   popup=popupImage(station_means$Filename,embed=TRUE)) %>%
  addScaleBar()

More leaflet - Mini Map

tmap_leaflet(tm_start2) %>% 
  addCircleMarkers(data=station_means,stroke = NA,
                   popup=popupImage(station_means$Filename,embed=TRUE)) %>%
  addMiniMap(zoomLevelOffset = -3)

More leaflet - measuring tool

bnds <- st_bbox(counties) # lng1, lat1, lng2, lat2
tmap_leaflet(tm_start2) %>% 
  addCircleMarkers(data=station_means,stroke = NA,
                   popup=popupImage(station_means$Filename,embed=TRUE)) %>%
  addMeasure()

Selective trendplots in use:

local_trendplot('Derry',rain2)

Self-Test Exercise:


Create a new pop-up map showing these plots when clicked instead of the original monthplots as shown earlier.


Conclusion

💡 New ideas

  • New R ideas
    • Pop-up information on leaflet maps
    • Interplay between tmap and leaflet
  • Next lecture - ggvis