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 rm(list=ls()) #Download some important packages library(maps) library(mapdata) library(maptools) library(rgdal) library(ggmap) library(ggplot2) library(rgeos) library(broom) library(plyr)
#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_Full_Clipped_Boundaries_in_the_United_Kingdom")
#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 print(gg)
#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")
Privacy & Cookies Policy
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.