In this lesson we are going to learn how to create a contour heatmap of spatial point data as well as create pie plots positioned on the centroid of a polygon.

Contour Heat Maps with ggmap

A contoured heat map is another way to demonstrate data density, especially if you do not have or do not desire to create a heatmap over a shapefile (like the country’s provinces). The contour heatmap uses two-dimentsional kernel density estimation in order to create the contoured heatmap of the spatial point data. Think of this as a histogram in two dimensions

Below we demonstrate how to do this using the crime data

library(ggmap)   ##load the ggmap package so we can access the crime data
data(crime)      ##load the crime data

We will plot the contour map over a ggmap:

houston <- get_map(location = "houston", zoom = 13) ##Get the houston map
houstonMap<-ggmap(houston, extent = "device")       ##Prepare Map

houstonMap +
  stat_density2d(aes(x = lon, y = lat, fill = ..level..,alpha=..level..), bins = 10, geom = "polygon", data = crime) +
  scale_fill_gradient(low = "black", high = "red")+
  ggtitle("Map of Crime Density in Houston")

plot of chunk unnamed-chunk-2

Once you do this, play with the number of bins to see how this variable will change the look of the contours. Try 5, 10, and 15. You can also experiment with changing the color of the heat map.

Pieplots over Polygons

Often times we want to understand the spatial nature of a categorical variable. One way to do this is to position multiple plots over their respective geographical area. To demonstrate this, we will load an unclassified data set about attacks in Afghanistan. This comes from the Worldwide Incidents Tracking System (WITS database) which is maintained by the National Counterterrorism Center. This data is available to download from CIS as a csv file.

Copy and paste the function below into your console (or source it from a file). This will load the Pie over Polygon procedure.

plotPiePoly <-function(data,shape,factor,main="Pie Plot",
           size=c(1,1),legend=TRUE,legend.pos="bottomright"){
    # Plots a Pie Plot over over Polygons in a SpatialPolygonDataFrame
    #
    # Args:
    #   data:       Spatial Points dataframe
    #   shape:          Shapefile  
    #   factor.column:  The column in the SpatialPointsDataFrame
    #   main:           the title of the graph
    #   size:           The size of the pieplot in inches
    #
    #   Notes:  This function requires the sp package.
    #
    #   Beskow: 03/30/11   
    #
    is.installed <- function(mypkg) is.element(mypkg, 
                                               installed.packages()[,1])
    if (is.installed(mypkg="sp")==FALSE)  {
      stop("sp package is not installed")}
    if (is.installed(mypkg="TeachingDemos")==FALSE)  {
      stop("TeachingDemos package is not installed")}
    if (!class(data)=="SpatialPointsDataFrame")  {
      stop("data argument is not SpatialPointsDataFrame")}
    require(sp)
    require(TeachingDemos)
    names(data)[grep(factor,names(data))]<-"factor"
    data.table<-table(data$factor)
    data.table<-sort(data.table[data.table>0],decreasing=TRUE)
    my.names<-names(data.table)
    palette(rainbow(length(my.names)))
    plot(shape)
    if(legend){
      legend(legend.pos, my.names, col=c(2:(length(my.names)+1)),
             text.col = "green4", pch = c(15), bg = 'gray90',cex=0.8)}
    for (i in 1:length(shape)){
      x<-!is.na(over(as(data,"SpatialPoints"),as(shape[i,],
                                                    "SpatialPolygons")))
      if(sum(x)>0){
        my.table<-table(as.factor(data$factor[x]))
        my.table<-my.table[my.table>0]
        table.Colors<-match(names(my.table),my.names)+1
        subplot(pie(my.table,col=table.Colors,labels=NA),
                coordinates(shape[i,])[1],
                coordinates(shape[i,])[2],size=size)
      }
    }
    palette("default")      
    mtext(main,cex=2)
  }

Now that you have the function in your working environment, you can load the relevant packages, read in the WITS data, and create your plot. Note that this plot looks better if you “zoom” in on it.

##Load Relevant Packages
library(sp)
library(TeachingDemos)
library(raster)

##Get the Afghanistan Shapefile
afg<-getData('GADM', country='AFG', level=1)  #Get the Province Shapefile for France

##Load the WITS data from CSV
wits_sp<-read.csv("wits_sp.csv",as.is=TRUE)

##Create the SpatialPointsDataFrame
coordinates(wits_sp)<-c("lon","lat")
proj4string(wits_sp)<-proj4string(afg)

##Now all you have to do is plot it!
plotPiePoly(data = wits_sp, 
            shape=afg, 
            factor = "flag", 
            size = c(0.5, 0.5), 
            legend = TRUE,
            main = "Sample Pieplot Over Polygon (WITS Data)")

plot of chunk unnamed-chunk-4

This allows you to visualize the spatial nature of a categorical variable.

Your Turn

Plot a contour heat map as well as a pieplot over province polygons map for your Montanoia IED data.