London map in 3 easy steps

By Data Tricks, 26 September 2017

In this tutorial we are going to create a great looking visualisation of London using postcode coordinates and the ggplot2 package in R.

1 Download OS data

First we need to download some postcode data. Ordnance Survey has a range of very good free downloads. The dataset we’re interested in is the Code-Point ® Open data which can be downloaded from here.

Download and unzip the file into a folder on your computer.

2 Read in the data and clean

The data is held in a folder called CSV in which there is a separate csv file for each postcode area (eg. SE or TN). The data cover the whole of the UK (excluding Northern Ireland) so we need to select the London postcodes and read in the relevant files.

setwd("C:/your-working-directory")
library(ggplot2)
filenames <- c("e.csv", "n.csv", "nw.csv", "se.csv", "sw.csv", "w.csv", "wc.csv", "ec.csv)
postcodes <- do.call(rbind,lapply(filenames,read.csv,header=FALSE))
postcodes <- postcodes[-which(postcodes$V3 == 0),]

Notice that the last line removes cases where the easting value is zero as there is at least one postcode in the csv files with coordinates of 0,0.

3 Plot the map using ggplot2

Now that we have read in our data we can use geom_point in the ggplot2 package to effectively create a scatterplot of all London postcodes from their easting and northing coordinates.

gg <- ggplot() + geom_point(data=postcodes, aes(x=V3, y=V4))
print(gg)

We can change the aspect ratio, apply some styling and remove the gridlines and background to make our map more visually appealing.

gg <- ggplot() + geom_point(data=postcodes, aes(x=V3, y=V4), color = '#800080', size=0.2, alpha=0.5)
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 = 'white'))
print(gg)

And there we have it – a pretty cool looking map of London. Of course, you can create a map of a different area of the UK simply by changing the filenames in Step 2.

Tip: The map might look different in the default viewer that you are using (eg. the Plots viewer in R Studio), as the viewer might resize the map to fit in the window without changing the size of the points. To get a better looking map, export it as an image and increase the dimensions. To get our map above we set the width as 1200px.

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.