Creating Maps in R (2019)

By Data Tricks, 2 February 2019

In an update to my previous article on creating maps in R, this post outlines how to create a heatmap of the UK using NUTS Level 2 boundaries (counties).

As a reminder, shapefiles for the UK are generally available at five levels of resolution: NUTS 1 (regions) through to NUTS 3 (districts), and finally LAU Level 1 (local authority districts) and LAU Level 2 (local authority wards). The further you go down that list, the more likely the regions are to change over time.

For the purpose of this article I’ll be using NUTS Level 2 data which can be downloaded from here:

Click on the Download button and then select the Shapefile option. Download and unzip the files into a folder on your computer.

Below I have copied the reproducible code (as of February 2019) to create the heatmap of the UK.

#Clear the memory
#Download some important packages

#Load the shapefile - make sure you change the filepath to where you saved the shapefiles
shapefile <- readOGR(dsn="C:/R projects/R gallery/Shapefiles Jan 2018", layer="NUTS_Level_2__January_2018__Boundaries")

#Reshape for ggplot2 using the Broom package
mapdata <- tidy(shapefile, region="nuts218nm") #This might take a few minutes

#Check the shapefile has loaded correctly by plotting an outline map of the UK
gg <- ggplot() + geom_polygon(data = mapdata, aes(x = long, y = lat, group = group), color = "#FFFFFF", size = 0.25)
gg <- gg + coord_fixed(1) #This gives the map a 1:1 aspect ratio to prevent the map from appearing squashed

#Create some data to use in the heatmap - here we are creating a random "value" for each county (by id)
mydata <- data.frame(id=unique(mapdata$id), value=sample(c(0:100), length(unique(mapdata$id)), replace = TRUE))

#Join mydata with mapdata
df <- join(mapdata, mydata, by="id")

#Create the heatmap using the ggplot2 package
gg <- ggplot() + geom_polygon(data = df, aes(x = long, y = lat, group = group, fill = value), color = "#FFFFFF", size = 0.25)
gg <- gg + scale_fill_gradient2(low = "blue", mid = "red", high = "yellow", na.value = "white")
gg <- gg + coord_fixed(1)
gg <- gg + theme_minimal()
gg <- gg + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), legend.position = 'none')
gg <- gg + theme(axis.title.x=element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank())
gg <- gg + theme(axis.title.y=element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank())

Tags: , , ,

2 thoughts on “Creating Maps in R (2019)”

  1. Matt says:

    Great post, thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *

Please note that your first comment on this site will be moderated, after which you will be able to comment freely.