Further Interactive Techniques

🔦 Overview


  • More on interaction
  • Interactive maps for tempooreal 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
## Source: local data frame [4 x 4]
## 
##    Year  Month Rainfall    Station
##   (dbl) (fctr)    (dbl)      (chr)
## 1  1850    Jan    169.0     Ardara
## 2  1850    Jan     96.9      Derry
## 3  1850    Jan    107.6 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)
}

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)
stations %>% mutate(Filename=paste0('mp ',Station,'.png')) -> files
files %>% select(Station,Filename) %>% head
## Source: local data frame [6 x 2]
## 
##       Station           Filename
##         (chr)              (chr)
## 1      Athboy      mp Athboy.png
## 2 Foulksmills mp Foulksmills.png
## 3   Mullingar   mp Mullingar.png
## 4     Portlaw     mp Portlaw.png
## 5    Rathdrum    mp Rathdrum.png
## 6 Strokestown mp Strokestown.png

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

Embedding Graphics

load("maps.RData")
leaflet(data=counties.spdf,height=430,width=600) %>% 
  addTiles %>% addPolygons(fillOpacity=0.4,weight=1,color='black',popup='<img src="test.png">') 

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
## Source: local data frame [6 x 2]
## 
##       Station                          Popup
##         (chr)                          (chr)
## 1      Athboy      <img src="mp Athboy.png">
## 2 Foulksmills <img src="mp Foulksmills.png">
## 3   Mullingar   <img src="mp Mullingar.png">
## 4     Portlaw     <img src="mp Portlaw.png">
## 5    Rathdrum    <img src="mp Rathdrum.png">
## 6 Strokestown <img src="mp Strokestown.png">
## Source: local data frame [6 x 2]
## 
##       Station
##         (chr)
## 1      Athboy
## 2 Foulksmills
## 3   Mullingar
## 4     Portlaw
## 5    Rathdrum
## 6 Strokestown
## Variables not shown: Popup (chr)

  • 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…


color_fun <- colorNumeric('Blues',station_means$mrain)
leaflet(data=station_means,height=430,width=600) %>% addProviderTiles('CartoDB.Positron')  %>%
  setView(-8,53.5,6) %>%
  addCircleMarkers(fillColor=color_fun(station_means$mrain),weight=0,
                                          fillOpacity = 0.85,popup=station_means$Popup) %>%
  addLegend(pal=color_fun,values=station_means$mrain,title="Rainfall",position='bottomleft')
  • Note that this will work if you run on your machine, but as yet doesn’t on this blog link.

Putting it together…


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.

  • Answer next week …

… but it looks like this:

  • Quick self-test: Identify the color scheme

More interaction - the ggvis package

library(ggvis)
rain %>% group_by(Year) %>%
  summarise(mr=mean(Rainfall)) %>% 
  ggvis(x=~Year,y=~mr) %>% layer_lines()

Storing plots to show later

rain %>% group_by(Year) %>%
  summarise(mr=mean(Rainfall)) %>% 
  ggvis(x=~Year,y=~mr) -> rain_ggv
  • Nothing plotted yet
  • But information for plot creation is in rain_ggv
  • Can add to this later on…

Employing a stored plot

rain_ggv %>% layer_lines(stroke := 'firebrick')

  • Note := for definition
    • ordinary = selects factor
  • ggvis plots are resizable

Re-employing a stored plot

rain_ggv %>% layer_points(fill := 'navy') %>% 
  layer_lines(stroke := 'firebrick')

Smoothing in ggvis

rain_ggv %>% layer_smooths(span=1,stroke := 'dodgerblue') 

  • span is the degree of smoothing
  • span=1 covers whole dataset, but is ‘tapered’

Smooth plus points


rain_ggv %>% layer_smooths(span=1,stroke := 'dodgerblue') %>% layer_points(fill := 'firebrick')

  • Demonstrates signal vs. noise comparison

Interactive smoothing


rain_ggv %>% layer_smooths(span=input_slider(0.1,1.5),stroke := 'dodgerblue') 
  %>% layer_points(fill := 'firebrick')
  • As yet, ggvis can’t do this in a simple presentation
  • But you can in RStudio

Interactive smoothing 2


rain_ggv %>% layer_points(fill := 'firebrick') %>% 
  layer_smooths(span=waggle(0.1,1.5),stroke := 'dodgerblue') 
  • As before, can’t yet embed in a presentation
  • waggle should be last item in pipeline
    • When R sees it, it starts waggling and ignores remainder

Neater Labelling


rain_ggv %>% layer_smooths(span=1,stroke := 'dodgerblue') %>% layer_points(fill := 'firebrick') %>%
  add_axis(type='x',format='4d',subdivide=10) %>% add_axis(type='y',title='Rainfall (cm per year)')

How format works in ggvis


  • Quite complex, but
    • 4d,5d etc means decimal occupying 4, 5 spaces
    • 4,d etc as above with commas after 1000’s
    • 6.2f display decimals to 2 places
    • 03d pad with leading zeroes - ie 007
  • See here for full information

Conclusion

💡 New ideas

  • New R ideas
    • Pop-up information on leaflet maps
    • ggvis and pipeline-based commands, for plots
    • smoothed items and span
  • Next lecture - Reproducible research