10 March 2016

## Making a data viz

SOMETIMES ANIMATION CAN BE USEFUL, though it is often misused. I’ve been tracking the week-to-week changes in mortgage rates, and animating with a GIF.

### Example animated gif with mortgage rates from 1/1/2013 to 3/10/2016

I build my gif using the R statistical package.

Perhaps I’ll explain more of the details later, but the R code below uses the ggplot2, ggthemes and animation packages to create the plots, style them, and save the animation.

#First we need to load the required packages, ggplot2, scales, and animation
require("animation")
library("ggplot2")
library("scales")

#We also use the ggthemes pacakged to style our graph
require('ggthemes')

# our data file is in a tab-delimited text file called "pmms30yr.txt" that has one column of dates and one column of rates

#turn the date into an R date
pmms30yr$date<-as.Date(pmms30yr$date, format="%m/%d/%Y")

#We only want data from 2013 to 2016, so we subset the data frame for dates after Jan 1, 2013:

d<-with(pmms30yr, pmms30yr[(date >= "2013-01-01"), ])

#Determine the length of the (trimmed) dataset

i0<-nrow(d)

oopt = ani.options(interval = 0.1)
saveGIF({for (i in 1:i0) {
g<-ggplot(data=d, aes(x=date,y=rate, label = rate))+geom_line(data=d[1:i,])+
scale_y_continuous(limits = c(3.25, 4.75)) + geom_point(data=d[i,],colour = "red", size = 3)+
scale_x_date(labels= date_format("%m-%Y"),
limits = as.Date(c('2013-01-01','2016-03-30'))) +

geom_text(data=d[i,],hjust = 0, nudge_x = 0.075,nudge_y=.075)+
theme(axis.title.x = element_blank()) +   # Remove x-axis label
ylab("")+xlab("")+
ggtitle("30-year fixed mortgage rate (%)")+
annotate("text",x=d[40,1], y = 3.30, label = "@lenkiefer, Source: Freddie Mac PMMS")+
annotate("text",x=d[i0-30,1], y=  4.65,
label=paste("Week ending: ",d[i,1]))+ theme_economist() + scale_colour_economist()
print(g)
ani.pause()
}
#Add a bunch of images to pause at end

for (i2 in 1:30) {
g<-ggplot(data=d, aes(x=date,y=rate, label = rate))+geom_line(data=d[1:i,])+
scale_y_continuous(limits = c(3.25, 4.75)) + geom_point(data=d[i,],colour = "red", size = 3)+
scale_x_date(labels= date_format("%m-%Y"),
limits = as.Date(c('2013-01-01','2016-03-30'))) +

geom_text(data=d[i,],hjust = 0, nudge_x = 0.075,nudge_y=.075)+
theme(axis.title.x = element_blank()) +   # Remove x-axis label
ylab("")+xlab("")+
ggtitle("30-year fixed mortgage rate (%)")+
annotate("text",x=d[40,1], y = 3.30, label = "@lenkiefer, Source: Freddie Mac PMMS")+
annotate("text",x=d[i0-30,1], y=  4.65,
label=paste("Week ending: ",d[i,1]))+ theme_economist() + scale_colour_economist()

print(g)

ani.pause()
}
},movie.name="your_awesome_gif.gif",ani.width = 500, ani.height = 300)