Source

Open Source / London Immigration.R

Full commit
##################################################
## London Data Maps Visualisation               ##
## Author: Mark Bulling                         ##
## Date: 2011-06-01                             ##
## Comments: code to generate maps of London    ##
##################################################

library(ggplot2)
library(maps)
library(sp)

gpclibPermit()

#### Read in shapefiles for UK LA's from GADM
con <- url("http://www.gadm.org/data/rda/GBR_adm2.RData")
print(load(con))
close(con)

#### Fortify this using ggplot2 features - this turns the shapefiles into a dataframe
ukmap <- fortify.SpatialPolygonsDataFrame(gadm, region="NAME_2")
ukmap$order <- rownames(ukmap) ### Order is important when drawing the map

#### Read in the immigration data from London datastore
url <- "http://data.london.gov.uk/datafiles/demographics/nino-registrations-overseas-borough-2009.csv"

london.data <- read.csv(url)

### Melt the data to turn it into something that can be cast
london.data.melt <- melt(x, id=c("Code", "Area", "Total.Number.of.Registrations", "MYE.Working.age.2008"))
london.data.cast <- cast(london.data.melt, variable~., fun.aggregate=sum)
colnames(london.data.cast) <- c("Area", "total")

london.data.cast <- london.data.cast[order(london.data.cast$total, decreasing=TRUE), ]
london.data.cast$rank <- as.numeric(rank(london.data.cast$total))

### Drop the data that is extraneous (not elegant)
london.data.melt <- merge(london.data.melt, london.data.cast, by.x="variable", by.y="Area")
london.data.melt <- subset(london.data.melt, as.numeric(rank)>=185)

### Merge on immigration data to the uk la map dataframe
ukmap.data <- merge(ukmap, london.data.melt, by.x="id", by.y="Area")
ukmap.data <- ukmap.data[order(ukmap.data$order), ]

### Drop other extraneous data
ukmap.data.sub <- subset(ukmap.data, value>0)
ukmap.data.sub <- subset(ukmap.data.sub, group!="London.1")

### Merging the data above messes up the order of the points, so reorder to 
ukmap.data.sub$order <- as.numeric(ukmap.data.sub$order)
ukmap.data.sub <- ukmap.data.sub[order(ukmap.data.sub$rank, ukmap.data.sub$group, ukmap.data.sub$order), ]

#### Plot the map - facetted by country of origin
ggplot(data = ukmap.data.sub, aes(x = long, y = lat, fill = cut_interval(log(value), n = 9), grouping = group))+
		geom_polygon()+
		theme_bw()+
		geom_path(colour="grey")+
		xlim(c(-0.6, 0.4))+
		ylim(c(51.25, 51.7))+
		facet_wrap(~variable)+
		scale_fill_brewer(palette = "PuRd", label = "Number of registered immigrants")+
		xlab("")+
		ylab("")