Search code examples
rggplot2geom-text

How do I deal with "Error in FUN(X[[i]],..." when trying to add text labels to points with geom_text?


I am brand spankin' new when it comes to R. Any help you can give me will be greatly appreciated.

I am using the choroplethr package to create maps by ZIP code. I want to add an overlay showing cities using geom_point.

My code is

t <- test.map +
  geom_point(data=lookup, aes(x=lat, y=lon), size=2, color="black", inherit.aes=FALSE) + 
  geom_text(aes(label=name),hjust=0, vjust=0)

where test.map is the plot from choroplethr, and lookup is a dataframe containing latitudes (lat), longitudes (lon), and location names (name).

geom_text returns the error:

Error in FUN(X[[i]], ...) : object 'name' not found

and I am not sure why.

Can you give me a hand?

Thanks!


Solution

  • The problem with OP's code is that geom_point and geom_text inherit data and aesthetics from what was used to create test.map

    If we want to use a different data set for additional layers we need to specify the data argument in each of them and also set inherit.aes to FALSE.

    test.map +
      geom_point(data=lookup, aes(x=lat, y=lon), size=2, color="black", inherit.aes=FALSE) +
      geom_text(data=lookup, aes(label=name), hjust=0, vjust=0, inherit.aes=FALSE)