Animation

Animation is surprisingly easy. The sliderInput() function, which provides an HTML widget that allows us to select a number along a line, has an optional animation function that will increment a variable by a set amount every time a specified unit of time elapses. This allows you to very easily produce a graphic that is animated.

In the following example, we are going to look at the monthly graph and plot a linear trend line through the first 20% of the data (0-20% of the data). Then, we are going to increment the percentage value that selects the portion of the data by 5% and plot a linear through that portion of data (5-25% of the data). Then, increment by 10-30% and plot another line, and so on.

The slider input is set up as follows, with an ID, label, minimum value, maximum value, initial value, step between values, and the animation options, giving the delay in milliseconds and whether the animation should loop:

sliderInput("animation", "Trend over time",  
  min = 0, max = 80, value = 0, step = 5,  
  animate = animationOptions(interval = 1000,  
    loop = TRUE))  
 

Having set this up, the animated graph code is pretty simple, looking very much like the monthly graph data except with the linear smooth based on a subset of the data instead of the whole dataset. The graph is set up as before and then a subset of the data is produced on which the linear smooth can be based:

groupByDate <- group_by(passData(), YearMonth, networkDomain) %>%  
summarise(meanSession = mean(sessionDuration, na.rm = TRUE),  
  users = sum(users),  
  newUsers = sum(newUsers), sessions = sum(sessions))  
groupByDate$Date <- as.Date(paste0(groupByDate$YearMonth, "01"),  
  format = "%Y%m%d")  
smoothData <- groupByDate[groupByDate$Date %in%  
  quantile(groupByDate$Date,  
    input$animation / 100,  
    type = 1) : quantile(groupByDate$Date,  
    (input$animation + 20) / 100,  
    type = 1),]  
 

We won't get too distracted by this code, but essentially, it tests to see which of the whole date range falls in a range defined by percentage quantiles based on the sliderInput() values. Take a look at ?quantile for more information.

Finally, the linear smooth is drawn with an extra data argument to tell ggplot2 to base the line only on the smaller smoothData object and not the whole range:

ggplot(groupByDate, aes_string(x = "Date",  
  y = input$outputRequired,  
  group = "networkDomain",  
  colour = "networkDomain")) + geom_line() +  
  geom_smooth(data = smoothData,  
    method = "lm", colour = "black")  

Not bad for a few lines of code. We have both ggplot2 and Shiny to thank for how easy this is.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.179.193