March 18, 2014

Try timeline with googleVis package

According to the post, googlevis package can manage timeline function. I'm a timeline enthusiast, so I can't help trying it!

Here's today's data.

# CRAN version does not support timeline function yet.
# You have to install from github.

# devtools::install_github("mages/googleVis")
library(XML)
library(reshape2)

res <- readHTMLTable("http://www.presidentsusa.net/presvplist.html")[[2]]
res.m <- melt(res, id.var=NULL)
res.m <- subset(res.m, nchar(value)>0 & complete.cases(res.m))
res.m$Name <- gsub("\\(.+\\)", "", res.m$value, perl=TRUE)
res.m$start <- as.integer(gsub(".+\\(|-.+|\\)", "", res.m$value, perl=TRUE))
res.m$end <- as.integer(gsub(".+-|\\)", "", res.m$value, perl=TRUE))
res.m[is.na(res.m$end),]$end <- res.m[is.na(res.m$end),]$start
res.m[res.m$Name %in% c("Joe Biden ","Barack Obama "),]$end <- 2013
res.m <- res.m[,c("variable", "Name", "start", "end")]
colnames(res.m)[1] <- "Position"
res.m$start <- as.Date(paste0(res.m$start, "-01-01"))
res.m$end <- as.Date(paste0(res.m$end, "-01-01"))
head(res.m)
##     Position               Name      start        end
## 2  President George Washington  1789-01-01 1797-01-01
## 3  President        John Adams  1797-01-01 1801-01-01
## 4  President  Thomas Jefferson  1801-01-01 1809-01-01
## 6  President     James Madison  1809-01-01 1817-01-01
## 10 President      James Monroe  1817-01-01 1825-01-01
## 11 President John Quincy Adams  1825-01-01 1829-01-01

And the result is as follows.

# prepare colors
library(colorspace)
hsv <- HSV(seq(0, 360, length = nrow(res.m)), 1, 1)
mycolor <- hex(hsv)[sample(nrow(res.m))]

# visualize
library(googleVis)
T <- gvisTimeline(res.m, 
                       barlabel="Name", 
                       rowlabel="Position",
                       start="start", 
                       end="end",
                       options=list(width=1000,
                                    height=150,
                                    colors=paste0("['", paste(collapse="','", mycolor), "']"), 
                       chartid="chart"))

print(T, "chart")

It is Very easy. To visualize simple timeline data, I will use this package.

No comments:

Post a Comment