Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
In this tutorial I will show you I build my election maps.
Preliminaries
Before we start, we need some data and a graphic tool for the plotting:
- I downloaded the data from http://www.landtagswahl-bw.de.
- I got the admin level 3 boundaries from http://www.gadm.
- dgd The graphics are generated with the great R-package ggplot2 developed by Hadley Wickham.
As the data has just the names and a special number of the communes, we need to get the geographic coordinates from them. For this task I used the package ggmap by which you can get the coords for your communes from google (Attention: just 2500 queries per day).
My geocode function:
getCoordsfromGoogle <- function(listofCities, printQuery=TRUE) { library(ggmap) n <- length(listofCities) coords <- data.frame(lon=rep(NA, n), lat=rep(NA, n)) for (i in 1:n) { c <- geocodeQueryCheck() if (printQuery) { print(c) } if (c > 0) { coords[i, ] <- geocode(listofCities[i]) } else { print("Your google query is zero.") return(coords) } } return(coords) }
Now we have to prepare or election data. I omit some manually preparation of the data. First load the shape data from gadm:
load("DEU_adm3.RData") bwk <- gadm[which(gadm$NAME_1 == "Baden-Württemberg"), ]
The election data is loaded into a data frame called lw I did a rbind with the coordinates I got by google and calculate the relative election results of the two groups:
lw$CDUrel <- (lw$CDU.CSU + lw$FDP) / lw$Gültige.Stimmen lw$SPDrel <- (lw$SPD + lw$GRüNE + lw$DIE.LINKE) / lw$Gültige.Stimmen lw$abs <- 100*(lw$CDUrel - lw$SPDrel)
Yet we are able to plot the first map with the raw data.
p <- ggplot() + geom_point(data = lw, mapping = aes(x=lon, y=lat, colour=abs), size = 3, alpha = 0.8) + scale_colour_gradient2(name = "Differenz \n Wahlergebnis", low = "darkred", mid = "white", high = "blue", guide = "colorbar") + ggtitle("Landtagswahl Baden-Württemberg 2011\n (Rohdaten)") p + geom_path(data = bwk, mapping = aes(x=long, y=lat, group=group), size = 0.125)
The following graphics shows the result. Part two will follow in the next days.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.