Last active
March 28, 2017 03:44
-
-
Save anhqle/5855730 to your computer and use it in GitHub Desktop.
[ggplot2, animation] Create animated choropleth map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
rm(list=ls()) | |
toInstall <- c("ggplot2", "maptools", "animation", "rgdal") | |
lapply(toInstall, library, character.only=TRUE) | |
# Load and clean World Governance Indicators (WGI) data | |
# Can be downloaded here https://dl.dropboxusercontent.com/u/18955935/wgi_final.RData | |
# Most of the cleaning involving matching World Bank naming system with that of the map | |
load('./data/wgi_cleaned.RData') | |
# Load world map shape file (Google "TM_WORLD_BORDERS_SIMPL-0.3") | |
world.map <- readOGR(dsn="./data", layer="TM_WORLD_BORDERS_SIMPL-0.3") | |
world.ggmap <- fortify(world.map, region = "NAME") | |
# Check the country names in WGI and world.ggmap and fix the unmatched | |
# Plot | |
saveSWF({ # Output a flash | |
for (i in c(1996, 1998, 2000, 2002:2011)) { | |
temp <- subset(na.omit(wgi[, c('year', 'country', 'cc_est')]), year==i) | |
choro <- merge(world.ggmap, temp, by.x="id", by.y="country") | |
choro <- choro[order(choro$order), ] # order matters in map data, so we must reorder | |
p <- ggplot(data=choro, aes(long, lat, fill=cc_est, group=group)) | |
print( | |
p + geom_polygon() + ylim(c(-60,85)) + # Fix the y-axis range for consistency between the years | |
scale_fill_gradient2("Control of\n corruption\n score", limits=c(-2.5,2.5)) + # Use scale_fill_gradient2 for contrast | |
labs(title=substitute(paste("Severity of corruption in the world, year ", i), list(i=i))) | |
) | |
} | |
}, swf.name="world_corruption.swf", interval=1, | |
ani.width=1200, ani.height=600, | |
swftools="C:/Program Files (x86)/SWFTools", | |
outdir=getwd()) | |
saveLatex({ # Output a pdf that can be embedded in latex documents | |
for (i in c(1996, 1998, 2000, 2002:2011)) { | |
temp <- subset(na.omit(wgi[, c('year', 'country', 'cc_est')]), year==i) | |
choro <- merge(world.ggmap, temp, by.x="id", by.y="country") | |
choro <- choro[order(choro$order), ] | |
p <- ggplot(data=choro, aes(long, lat, fill=cc_est, group=group)) | |
print( | |
p + geom_polygon() + ylim(c(-60,85)) + | |
scale_fill_gradient2("Control of\n corruption\n score", limits=c(-2.5,2.5)) + | |
labs(title=substitute(paste("Severity of corruption in the world, year ", i), list(i=i))) | |
) | |
} | |
}, ani.basename = "world_corruption", interval=1, | |
ani.width=900, ani.height=450, | |
ani.opts="autoplay,loop,controls,width=\\linewidth", | |
latex.filename = "world.corruption.tex", | |
outdir=getwd()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment