-1

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!

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
jubjub
  • 107
  • 8
  • It's hard to troubleshoot this without knowing what your `congress` dataset looks like... – Z.Lin Sep 06 '18 at 01:30
  • Fair point. Thanks for taking the time to respond anyway. I downloaded the data from the US Census cartographic boundary files website. I'm not sure if this helps, but the data has 11 variables. One is _DISTRICT_, which refers to the congressional district by number. I use that to create my _DistrictLabel_. – jubjub Sep 06 '18 at 05:29
  • Try and post a small subset of that data that can reproduce your error. – kabanus Sep 06 '18 at 12:14
  • 1
    `DistrictLabel` is a column in `congress@data`, but you're passing `congress` as an argument to `data = `, and consequently `aes` can't find `DistrictLabel`. Try changing to `geom_text( data = congress@data, ... )`. – Artem Sokolov Sep 06 '18 at 14:17

1 Answers1

2

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) 
Jul
  • 1,129
  • 6
  • 12