2

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.

Dan
  • 1,711
  • 2
  • 24
  • 39
  • 1
    Have you tried geom_sf_label? https://yutannihilation.github.io/ggsflabel/reference/geom_sf_label.html – mrhellmann Nov 04 '20 at 22:36
  • @mrhellmann Certainly tried it. Version 0.0.1 cannot be installed on my machine; (issue opened here: https://github.com/yutannihilation/ggsflabel/issues/3) but the question is really about going from **sf** to **tidy data** that can be plotted – Dan Nov 04 '20 at 22:37
  • If adding x & y coordinates to the sf object (in a non-list, non-geometry) column is what you're looking for this might help: https://stackoverflow.com/a/61745776/7547327 – mrhellmann Nov 04 '20 at 22:50

1 Answers1

3

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

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87