Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save datagistips/2868109 to your computer and use it in GitHub Desktop.
Save datagistips/2868109 to your computer and use it in GitHub Desktop.
Isarithmic Choropleth - election results
library(rgdal)
# DATA
# http://professionnels.ign.fr/ficheProduitCMS.do?idDoc=6185461
cities <- readOGR("C:/DATAS/GEOFLA/COMMUNES/COMMUNE.SHP", "COMMUNE")
# http://www.data-publica.com/opendata/13495--resultats-du-deuxieme-tour-de-l-election-presidentielle-2012
votes <- read.csv2("IN/votesResults2012.csv",sep=",", quote="\"")
# VOTES TO SPATIAL DATA "
votes$pc.sar <- votes$results.sarkozy / votes$results.exprimes
votes$pc.hol <- votes$results.hollande / votes$results.exprimes
nmatch <- which(is.na(match(cities@data$INSEE_COM, votes$commune.code)))
print(cities@data[nmatch, c("INSEE_COM", "NOM_COMM")])
cities <- cities[-nmatch, ]
m <- merge(cities@data, votes, by.x="INSEE_COM", by.y="commune.code", all.x=TRUE)
cities <- spChFIDs(cities, as.character(cities$INSEE_COM))
rownames(m) <- as.character(m$INSEE_COM)
cities <- SpatialPolygonsDataFrame(as(cities, "SpatialPolygons"), data=m)
nCuts <- 100 # num
# VOTES - CUTS
cutsVotes <- cut(cities$pc.sar, 100)
cutsVotesId <- as.numeric(cutsVotes)
# VOTES - COLORS
palVotes <- colorRampPalette(c("red", "white", "blue"))
colsVotes <-palVotes(100)[cutsVotesId]
# POPULATION - CUTS
par(mfrow=c(1,2))
hist(cities$POPULATION)
hist(log(cities$POPULATION))
dev.off()
cutsPop <- cut(log(cities$POPULATION), 100) # log to exponentially diminish high values, 100 equal interval cuts
cutsPopId <- as.numeric(cutsPop) # we get the cut ID (1-100)
# POPULATION - PALETTE
seqTrsp <- seq(0, .8, length.out=nCuts)
palPop <- rgb(0, 0, 0, seqTrsp)
palPop <- rev(palPop) # when reversing, from opaque (low values) to transparent (high values)
colsPop <- palPop[cutsPopId]
# PLOT
plot(cities, col=colsVotes, border=NA)
plot(cities, col=colsPop, border=NA, add=T)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment