Skip to content

Instantly share code, notes, and snippets.

@vapniks
Last active April 11, 2018 04:01
Show Gist options
  • Save vapniks/c1b3a943199cd706383f83b0c1269420 to your computer and use it in GitHub Desktop.
Save vapniks/c1b3a943199cd706383f83b0c1269420 to your computer and use it in GitHub Desktop.
Some examples of how to use geocode data of different formats with R.
# Some examples of how to use geocode data of different formats.
## load libraries
library("magrittr")
library("eurostat")
library("eurostat")
library("ggplot2")
library("countrycode")
library("rgdal")
library("colorbrewer")
## plotting NUTS shape files
eurNUTSmap <- rgdal::readOGR(dsn = "~/Data/geocodes_and_postcodes/NUTS_2010_60M_SH/Data", layer = "NUTS_RG_60M_2010")
nuts0map <- subset(eurNUTSmap, STAT_LEVL_==0) # countries
nuts1map <- subset(eurNUTSmap, STAT_LEVL_==1) # regions containing between 3 & 7 million people
nuts2map <- subset(eurNUTSmap, STAT_LEVL_==2) # subregions containing between 800,000 and 3,000,000 people
### plot outlines of level 2 NUTS areas
plot(nuts2map) # plot subregions
plot(nuts1map) # plot regions
plot(nuts0map) # plot countries
### change projection
oldprojection <- proj4string(nuts2map) # save copy of old projection information
nuts0map2 <- spTransform(nuts0map, CRS("+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs")) # change to projection used by google maps
dev.new() # open a new plotting device
plot(nuts0map2) # plot with the google maps projection
### Download eurostat data for choropleth graph
unempdata <- getEurostatRCV(kod = "lfst_r_lfu3rt") # unemployment rates
unempdata20150101 <- subset(unempdata,(age=="Y20-64") & (sex=="T") & (time=="2015-01-01"),select=c("geo","values")) # select a subset
### Add to shapes data
nuts0map2@data <- data.frame(nuts0map2@data, unempdata20150101[match(nuts0map2@data$NUTS_ID,unempdata20150101$geo), ])
### Create a colour scheme
mapcolours <- brewer.pal(5, "Reds") # 5 different shades of red
unempbreaks <- classIntervals(nuts0map2@data$values, n = 5, style = "fisher", unique = TRUE)$brks # create cutpoints
unempcategories <- findInterval(nuts0map2@data$values, unempbreaks, all.inside = TRUE) # quantize unemployment data
### plot choropleth graph of unemployment levels of EU countries in 2015-01-01
plot(nuts0map2, col=mapcolours[unempcategories], axes = FALSE, border = NA)
### add country borders to map
countryborders <- nuts0map2[nuts0map2@data$STAT_LEVL_ == 0, ]
plot <- plot(countryborders, border = "#707070", add = TRUE)
### add legend
locator() # first find coordinates on map: left click where you want the legend on the map, then right click the map
legend(x = -7080915, y = 8730220, legend = leglabs(round(breaks, digits = 2), between = " to <"), fill = mapcolours, bty = "n", cex = 0.7, title = "Unemployment Rate for\n 20-64yr olds in 2015")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment