Search code examples
rshapefileggmap

Add a column to data used with ggmap


I have a shape file of Statistical Local Areas (similar to postcode) in Australia. You can download it here, the file is named "Statistical Local Areas ASGC Ed 2011 Digital Boundaries in ESRI Shapefile Format" (at time of writing, it's the second link).

I am trying to map the SLAs on a ggmap plot, using a Population field from a secondary table to provide the colour mapping. Here's what I've got thus far:

library(tidyverse)
library(ggmap)
library(rgdal)

pops <- read_csv('http://mm-c.me/work/SlaPopulations.csv', col_types = "ci")

slas <- readOGR(dsn="SLA",layer="SLA11aAust")

aus4 <- get_map("Australia",zoom=4)
ggmap(aus4)

ggmap(aus4)+
  geom_path(data=slas, color = "black", aes(x=long,y=lat, group = group))

#Create a copy so we don't accidentally break the original
slasextended <- slas

slasextended@data <- slasextended@data %>% 
  left_join(pops)

#Throws an error 
#Error in FUN(X[[i]], ...) : object 'Population' not found
ggmap(aus4)+
  geom_polygon(data=slasextended, 
               color = "black", 
               aes(x = long, 
                   y = lat, 
                   group = group, 
                   fill = Population)) 

This approach is based on questions like this one, which suggest to treat the @data object as a data frame and then add columns to it. The problem is that it seems like ggmap can't find the data to use for its display.

How do I do this? Am I doing things entirely backward somehow or something?


Solution

  • According to the ggplot2 tutorial, spatial objects should be transformed to a data frame to work properly with ggplot:

    slasextended@data <- slasextended@data %>% 
      left_join(pops)
    slasextended@data$id <- rownames(slasextended@data)
    slasextended.points <- fortify(slasextended, region = "id")
    slasextended.df <- left_join(slasextended.points, 
        slasextended@data, by = "id") 
    

    The resulted standard data frame slasextended.df should be used for further plotting instead of the SpatialPolygonsDataFrame slasextended:

    test_plot <- ggmap(aus4) +
      geom_polygon(data = slasextended.df, 
                   color = "black", 
                   aes(
                        x = long, 
                        y = lat, 
                        group = group, 
                        fill = Population)
                   ) +
      scale_fill_distiller(palette = "Greens", 
        na.value = "white")
    

    Hope, it'll be helpful.