Analytics>Forward 2019

Animate your plots

Zeydy Ortiz, Ph. D. - http://linkedin.com/in/zortiz - @Dr_ZOrtiz
March 8, 2019

Animation is fun and easy!

Basic plot

plot of chunk unnamed-chunk-1

library(ggplot2)
library(ggthemes)
library(gganimate)

# Data from Rick Pack
# https://raw.githubusercontent.com/
# RickPack/AnalyticsForward_2019/
# master/AnalyticsForward_Registrations.csv
fileURL <- "RSVPdata.csv"
RSVPdata <- read.csv(file=fileURL)

ggplot(RSVPdata, 
       aes(x=days_to_event, 
           y=dates_yes_cumsum, 
           color=factor(yes_year))) + 
  geom_line()

Add Style

# color blind palette
cbPalette <- c("#999999", "#E69F00", "#56B4E9", "#009E73", "#000000")

g <- ggplot(RSVPdata, 
      aes(x=days_to_event, y=dates_yes_cumsum, color=factor(yes_year))) + 
    geom_line(size=1) + scale_color_manual(values=cbPalette) +
    scale_x_reverse() + # needed to reverse the x axis

  labs(title="Analytics>Forward RSVPs per year", color="Year",
       x="Days to the event", y="Total YES RSVPs", 
       caption="Source: @rick_pack2") +

  # theme settings
  theme_bw (base_size=16) +
    theme(plot.title=element_text())+
    theme(plot.caption=element_text(hjust=0,vjust=1,margin=margin(t=10)))+
    theme(plot.margin=unit(c(0.25,0.25,0.25,0.25),"cm"))

Add Style: Let's see

plot of chunk unnamed-chunk-4

Animate

plot of chunk unnamed-chunk-5

# add labels to each line, eliminate the legend and add transition 
g +  
  aes(label=yes_year) + 
  geom_text(size=5) + 
  theme(legend.position="none") +
  transition_reveal(days_to_event)

Oops! Let's try this instead

# Calculating the range for the x axis
# Hack to make sure animation from left to right 
starting <- max(RSVPdata$days_to_event)
ending <- min(RSVPdata$days_to_event)

# Animation settings from http://lenkiefer.com/2019/01/13/go-go-animate/
anim <- g +  aes(label=yes_year) + geom_text(size=5) + 
  theme(legend.position="none") +
  transition_reveal(days_to_event, range=c(starting, ending))

Wrapping it up!

plot of chunk unnamed-chunk-8

# use end_pause=20 to hold last frame for 20 frames (~2 seconds)
animate(anim, end_pause=20, width=800, height=600)

anim_save(file="AF_RSVP.gif", animation = last_animation())

Summary

To make an animation we need:

install.packages("gganimate")
install.packages("gifski") # renderer for gganimate

library(gganimate)

# g is a plot created with ggplot()

# Animation settings from http://lenkiefer.com/2019/01/13/go-go-animate/
anim <- g +  aes(label=yes_year) + geom_text(size=5) + 
  transition_reveal(days_to_event, range=c(starting, ending))

# use end_pause=20 to hold last frame for 20 frames (~2 seconds)
animate(anim, end_pause=20, width=800, height=600)
anim_save(file="AF_RSVP.gif", animation = last_animation())