Search code examples
rggplot2ggmap

Labeling polygons with ggmap


I think I must be overlooking something very simple here.

I'd like to apply labels to a set of polygons. Specifically, I'm trying to place labels on a handful of California congressional districts.

I begin by getting the basemap (socal) and overlaying data from my district SPDF (congress) over it:

socal <- get_map(location = "Riverside, USA", zoom = 8, source = "google", 
                 maptype = "roadmap")

somap <- ggmap(socal) +
  geom_polygon(data = congress, 
               aes(x = long, y = lat, group = group), 
               fill = "#F17521", color = "#1F77B4", alpha = .6)

So far, so good.

But then I'd like to label each polygon, so I create a new variable:

congress@data$DistrictLabel <- paste("CD", congress@data$DISTRICT, sep = "")

And when I try to add this to my map...

somap + geom_text(data = congress, aes(x = long, y = lat, label = DistrictLabel))

I get the following error:

Error in eval(expr, envir, enclos) : object 'DistrictLabel' not found

I know I'm overlooking something obvious, but I can't figure out what it is! Any help would be much appreciated.

Thanks!


Solution

  • For labels, I usually derive the polygons centroids first and plot based on those. I don't think ggplot2 has any automatic way to position text labels based on polygons. I think you have to specify it. Something like the following should work:

    library(dplyr)
    library(sp)
    library(rgeos)
    library(ggplot2)
    
    ##Add centroid coordinates to your polygon dataset
    your_SPDF@data <- cbind(your_SPDF@data,rgeos::gCentroid(your_SPDF,byid = T) %>% coordinates())
    
    ggplot(your_SPDF) +
      geom_polygon(data=your_SPDF,aes(x = long, y = lat, group = group), 
                                    fill = "#F17521", color = "#1F77B4", alpha = .6) +
      geom_text(data = your_SPDF@data, aes(x = x, y = y),label = your_SPDF$your_label)