Let's say I want to add labels to a geom_sf() plot, to get the following:
as of Nov/2020 the method does not exist, thus I get a warning and nothing gets plotted when I try:
library(sf)
nc <- st_read(system.file("shape/nc.shp", package="sf"))
ggplot() +
geom_sf(data = nc, aes(label = CNTY_ID))
Warning message:
Ignoring unknown aesthetics: label
When trying to add labels manually, via geom_text(), I can't figure out how to go from nc to "nc2" which I can use in a ggplot:
If I try the following, output is not as expected:
nc2 <- nc %>% st_centroid() %>% # ok, transform multypoligon to centroid
as.data.frame() # does not return something useful, WHY ?
but if I do:
nc2 <- nc %>% st_centroid() %>%
as_Spatial() %>% # this is nonsense, why ?
as.data.frame()
Now, using the following I can get the initially desired plot with proper labels.
ggplot() +
geom_sf(data = nc) +
geom_text(data=nc2, aes(coords.x1, coords.x2, label=CNTY_ID))
What is the recommended way to go from sf to tibble/data.frame to ggplot? Seems to me this is an ordinary task, and having to go through two steps (as_Spatial() + as.data.frame()) is wrong.