How do I plot a choropleth or thematic map using ggplot2 from a KML data source?
Example KML: https://dl.dropbox.com/u/1156404/nhs_pct.kml
Example data: https://dl.dropbox.com/u/1156404/nhs_dent_stat_pct.csv
Here’s what I’ve got so far:
install.packages("rgdal")
library(rgdal)
library(ggplot2)
fn='nhs_pct.kml'
#Look up the list of layers
ogrListLayers(fn)
#The KML file was originally grabbed from Google Fusion Tables
#There's only one layer...but we still need to identify it
kml=readOGR(fn,layer='Fusiontables folder')
#This seems to work for plotting boundaries:
plot(kml)
#And this:
kk=fortify(kml)
ggplot(kk, aes(x=long, y=lat,group=group))+ geom_polygon()
#Add some data into the mix
nhs <- read.csv("nhs_dent_stat_pct.csv")
kml@data=merge(kml@data,nhs,by.x='Name',by.y='PCT.ONS.CODE')
#I think I can plot against this data using plot()?
plot(kml,col=gray(kml@data$A.30.Sep.2012/100))
#But is that actually doing what I think it's doing?!
#And if so, how can experiment using other colour palettes?
#But the real question is: HOW DO I DO COLOUR PLOTS USING gggplot?
ggplot(kk, aes(x=long, y=lat,group=group)) #+ ????
So my question is: how do I use eg kml@data$A.30.Sep.2012 values to colour the regions?
And as a supplementary question: how might I then experiment with different colour palettes, again in the ggplot context?
Plotting maps in R is very often a pain. Here’s an answer which largely follows Hadley’s tutorial at https://github.com/hadley/ggplot2/wiki/plotting-polygon-shapefiles
Note: I got a message about orphan holes. I included the following line after reading https://stat.ethz.ch/pipermail/r-help/2011-July/283281.html