Object 'x' not found using points to label a map

I am trying to get an Argentinian map with a word in the center of each state:

library(rgdal)
library(sf)
library(raster)
library(tidyverse)

arg <- getData("GADM",country="ARG",level=1)

arg_sf<-st_as_sf(arg)[c("NAME_1","geometry")]

#I created a center point to use as coordinates for my words
arg_sf$center <- st_transform(arg_sf, 29101) %>% 
st_centroid() %>% 
# this is the crs from d, which has no EPSG code:
st_transform(., '+proj=longlat +ellps=GRS80 +no_defs') %>%
# since you want the centroids in a second geometry col:
st_geometry()
#I will use numbers instead of words, to simplify it.
arg_sf$words<-c(10,10,10,10,10,10,10,10,10,10,
                20,20,20,20,20,20,20,20,20,20,
                25,25,25,25)

map<-ggplot(data = arg_sf) +
  geom_sf(aes(fill=words))+
  scale_fill_manual(values = rainbow(3))+
  ggtitle("Google Trends de Argentina")+
  geom_text(data = arg_sf$center, mapping = aes(x=X, y=Y, label=words))

map

I have the folloging error:

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

If I use str(final), the points are using XY as axis, I am not sure why it is not recognizing it as a valid point.

I believe you should be able to achieve your aim with a simple geom_sf_text() call in your ggplot object; consider something along these lines (note the use of fun.geometry = sf::st_centroid - for lat lon data it comes with a warning, but the resulting map does not look too bad; perhaps except the horseshoe-like shaped Salta province)

library(rgdal)
library(sf)
library(raster)
library(tidyverse)

arg <- getData("GADM",country="ARG",level=1)

arg_sf<-st_as_sf(arg)[c("NAME_1","geometry")]

arg_sf$words<-c(10,10,10,10,10,10,10,10,10,10,
                20,20,20,20,20,20,20,20,20,20,
                25,25,25,25)

map<-ggplot(data = arg_sf) +
  geom_sf(aes(fill=words))+
  ggtitle("Google Trends de Argentina")+
  geom_sf_text(mapping = aes(label=words), fun.geometry = sf::st_centroid)

map

Thank you so much! I did not know about geom_sf_text. You totally solved my problem! You saved me hours of work.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.