UK population density map in R

By Data Tricks, 26 July 2018

This tutorial will guide you through the process of creating a unique population density map of the UK in R.

1 Download postcode data

In this tutorial we will use UK postcode data which is available for free from Ordnance Survey:

Once you’ve downloaded and unzipped the files (which will come as individual csv files for each top-level postcode), save them all in a single folder.

2 Read in postcode data


#Get all filenames and read in the postcodes
filenames <- dir("C:/your-working-directory") #get file names
postcodes <-,lapply(filenames,read.csv,header=FALSE)) #read in all files and bind
postcodes <- postcodes[-which(postcodes$V3 == 0),] #remove lines where V3 is zero

The code above reads all the csv files that you saved in your working directory and merges them using the rbind function. The last line simply removes anomalies in the data where V3 is zero.

3 Create the map

Now we can use ggplot2 to create the map using geom_point. Essentially all we need to do is to plot a scatter plot of all the postcodes’ coordinates (V3 and V4 values) using semi-transparent markers (use alpha in geom_point).

gg <- ggplot() + geom_point(data=postcodes, aes(x=V3, y=V4), color="#ff9900", size=0.2, alpha=0.3)
gg <- gg + coord_fixed(1)
gg <- gg + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())
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())
gg <- gg + theme(panel.background = element_rect(fill = 'black'))

The final result is not a true population density map because the postcode data includes PO Boxes and there will be differences in the number of people dwelling in each postcode. But it does provide an interesting map resembling a night time satellite image.


Tags: , , , , ,

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.

You might also like

The hidden art in pi

A series of visualisations created using the ggplot2 package in R and the first million digits of pi.

Read more

Violin plot in ggplot2

Create violin plots in R with the ggplot2 package.

Read more

Creating Maps in R (2019)

Creating a heatmap of the UK in R

Read more

Leaflet maps in R

Create interactive location maps in R and embed onto websites or other applications.

Read more

Line chart with smoothed conditional mean

Create a smoothed conditional mean through a scatter plot, or a line of best fit using ggplot2 and geom_smooth.

Read more