sf to data.frame: why as_Spatial needed before as.data.frame

Viewed 144

Let's say I want to add labels to a geom_sf() plot, to get the following:

enter image description here

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 ?

enter image description here

but if I do:

nc2 <- nc %>% st_centroid() %>%  
  as_Spatial() %>%                     # this is nonsense, why ?
  as.data.frame()

enter image description here

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.

1 Answers

You can use stat_sf_coordinates with geom = "text" in ggplot. You don't even need to create a second data frame; you can pass st_centroid as a parameter.

The following is actually a full reprex that should work for anyone who has recent versions of ggplot2 and sf installed:

ggplot2::ggplot(sf::st_read(system.file("shape/nc.shp", package = "sf"))) +
  ggplot2::geom_sf() +
  ggplot2::stat_sf_coordinates(fun.geometry = sf::st_centroid,
                               ggplot2::aes(label = CNTY_ID), geom = "text")

enter image description here

Related