Plotting Choropleth Maps from KML Data Using ggplot2

ggplot2, kml, r

Solution

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

library(maptools)
library(rgdal)
library(ggplot2)
library(plyr)

fn='nhs_pct.kml'
nhs <- read.csv("nhs_dent_stat_pct.csv")

kml <- readOGR(fn, layer="Fusiontables folder")

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

slot(kml, "polygons") <- lapply(slot(kml, "polygons"), checkPolygonsHoles)

## The rest more or less follows Hadley's tutorial 
kml.points = fortify(kml, region="Name")
kml.df = merge(kml.points, kml@data, by.x="id",by.y="Name",sort=FALSE)
kml.df <- merge(kml.df,nhs,by.x="id",by.y="PCT.ONS.CODE",sort=FALSE,all.x=T,all.y=F)

## Order matters for geom_path!
kml.df <- kml.df[order(kml.df$order),]

nhs.plot <- ggplot(kml.df, aes(long,lat,group=group,fill=A.30.Sep.2012)) + 
  geom_polygon() +
  geom_path(color="gray") +
  coord_equal() +
  scale_fill_gradient("The outcome") + 
    scale_x_continuous("") + scale_y_continuous("") +   theme_bw()

Problem

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?

Original source

Related problems