## read data cases = read.csv("h1n1_cases.csv",row.names=1) deaths = read.csv("h1n1_deaths.csv",row.names=1) ## derive first case firstcase <- apply(cases==0,1, function(z) {max(which(z))})+1 firstcase[!is.finite(firstcase)] <- 1 firstcase <- firstcase[rownames(cases) %in% state.name] ########### ## maps with the ggplot2 package library(ggplot2) library(maps) states <- map_data("state") choro <- merge(states, data.frame(region=tolower(names(firstcase)),firstcase)) choro <- choro[order(choro$order), ] g1 = ggplot(choro,aes(x=long,y=lat, group=group, fill=firstcase)) g1+geom_polygon()+scale_fill_gradient(low="red",high="blue") ## g1+geom_polygon()+facet_wrap(~firstcase)+theme_bw() ######################## ## with the latticeExtra package library(latticeExtra) tmpdat <- data.frame(state=tolower(rownames(cases)), total=cases[,ncol(cases)]) state.map <- map('state', plot = FALSE, fill = TRUE) ## HACK: erase region distinctions from states state.map$names <- sapply(strsplit(state.map$names,":"),"[[",1) ## plot plot(mapplot(state~total, map=state.map, data=tmpdat), split=c(1,1,1,2)) tmpdat2 <- data.frame(state=tolower(rownames(deaths)), total=deaths[,ncol(deaths)]) plot(mapplot(state~total, map=state.map, data=tmpdat2), split=c(1,2,1,2),newpage=FALSE) ## to superimpose numbers of cases: tmpdat = subset(tmpdat,state %in% tolower(state.name)) ### plot numbers as well? mapplot(state~total, map=state.map, data=tmpdat, panel=function(x,data,map,...) { panel.mapplot(x,map,...) panel.text(state.center$x,state.center$y, tmpdat$total,cex=0.8) }) ########### ## base graphics case2 <- cases[rownames(cases) %in% state.name,] ## animation -- plot symbols state.map <- map('state') par(xpd=NA) apply(case2,2,symbols,x=state.center$x,y=state.center$y, add=TRUE,fg="red",bg=rgb(1,0,0,0.1), inches=0.2) ## animation -- pause, add title (badly) while (TRUE) { map('state') par(xpd=NA) for (j in 1:ncol(case2)) { Sys.sleep(0.1) ## wait 0.1 seconds if (j>1) title(colnames(case2)[j-1],col.main="white") title(colnames(case2)[j]) symbols(case2[,j],x=state.center$x,y=state.center$y, add=TRUE,fg="red",bg=rgb(1,0,0,0.1), inches=0.2) } } #### ## polygons in base graphics??? haven't figured this out yet ... m = map('state',plot=FALSE) truncnames <- sapply(strsplit(m$names,":"),"[[",1) ## pcols <- rev(hsv(h=1,s=seq(0.1,1,length=8))) pcols <- rainbow(8) ## pcols <- gray((0:7)/7) casecat <- as.numeric(cut(log10(1+cases[-8,31]),8)) pcols2 <- pcols[casecat] cframe <- data.frame(cases=cases[-8,31], state=tolower(cases[-8,1]), col=pcols2, casecat=casecat, stringsAsFactors=FALSE) cols = merge(cframe, data.frame(tnorder=1:length(truncnames),state=truncnames)) map('state', fill=TRUE, col=cols$col) ## off because Alaska and Hawaii are out???