Skip to content

Instantly share code, notes, and snippets.

@stared
Last active November 21, 2019 12:18
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save stared/fbca436c885c430a314a to your computer and use it in GitHub Desktop.
Save stared/fbca436c885c430a314a to your computer and use it in GitHub Desktop.
Plot of Europe (choropleth) in R/ggplot, using NUTS data
# install necessary packages
library(dplyr)
library(maptools)
library(ggplot2)
#library(ggmap) # only for superimposing with Google maps
library(doBy)
# to make fortify possible without errors
library(gpclib)
gpclibPermit()
# requires downloading and unzipping NUTS_2013_01M_SH.zip from
# http://ec.europa.eu/eurostat/web/gisco/geodata/reference-data/administrative-units-statistical-units
eurMap <- readShapeSpatial("NUTS_2013_SHP/data/NUTS_RG_01M_2013.shp")
# only main adm level
eurMap <- subset(eurMap, nchar(as.character(NUTS_ID)) == 2)
# EL for Grece, UK for United Kingdom
eurMapDf <- fortify(eurMap, region='NUTS_ID')
# we assume two columns: CountryCode and NGA_Coverage
eurData <- read.csv("./NGA_coverage-ISO2.csv", stringsAsFactors = F)
# merge map and data
eurMapDataDf <- merge(eurMapDf, eurData, by.x="id", by.y="CountryCode")
# sort, so that polygons are drawn correctly
eurMapDataDf <- eurMapDataDf[order(eurMapDataDf$order),]
# limit data to main Europe
eurMapDataDf <- subset(eurMapDataDf, long > -15 & long < 32 & lat > 34 & lat < 75)
# add text; instead of mean I do middle (not to be to biased towards detailed coastlines)
middle = function (x) {
(max(x) + min(x)) / 2
}
txtVal <- summaryBy(long + lat + NGA_Coverage ~ id, data=eurMapDataDf, FUN=middle, keep.names=T)
# inverse order (to have visible borders)
p <- ggplot(data=eurMapDataDf) +
geom_polygon(aes(x=long, y=lat, group=group, fill=NGA_Coverage)) +
geom_path(aes(x=long, y=lat, group=group), color='black', alpha=.5) +
geom_text(aes(x=long, y=lat, label=sprintf("%.0f%%", NGA_Coverage)), data=txtVal, col="gray", cex=3) +
scale_fill_gradient2(low = "red", mid = "white", high = "blue") +
theme_bw() +
coord_equal()
ggsave("NGA_Coverage.png")
CountryCode NGA_Coverage
MT 100
BE 98.84
NL 98.41
LT 97.29
LU 94.42
DK 91.7
LV 89.58
PT 89.11
UK 88.55
AT 88.16
EE 83.13
DE 80.8
CY 80.11
HU 79.68
SI 78.21
SE 76.4
FI 75.09
ES 73.23
IE 70.74
BG 69.4
RO 69.24
CZ 67.31
SK 62.51
HR 56.95
PL 53.37
FR 42.61
IT 36.3
EL 34.01