0

I am attempting to label polygons from a spatial feature data frame using ggplot2. I am trying to replicate the description here under the heading, "Download Some Boundary Data: State/County/HUC"

This is my code to try to get the lat and lon values to use for the label location in geom_text():

selected_sites <- arc.open(survey_sites)
ss <- arc.select(selected_sites)
ss_shape <- arc.data2sf(ss)
refcode_list <- ss$refcode

ss_shape <- ss_shape %>%
  mutate(lon=map(geometry, ~st_centroid(.x)[[1]]),
         lat=map(geometry, ~st_centroid(.x)[[2]]))

I keep getting the following error:

Error in mutate_impl(.data, dots) :
Evaluation error: .x is not a vector (closure).

Richard Telford
  • 8,423
  • 6
  • 34
  • 48
mmoore
  • 174
  • 8
  • 1
    Why not just simply save the centroids to a new `sf` object that you can pass to `geom_text()`? eg) `ss_centroids – Chris Aug 23 '18 at 21:25
  • This works for me if I use sample data from the spdep package converted to an sf class polygons data frame, and use library(purrrr). Can you make a reproducible example? Also, this is really inefficient because you are calling `st_centroid` twice. Much quicker and direct to cbind the coordinates: `G = cbind(G, st_coordinates(st_centroid(G$geometry)))` – Spacedman Aug 23 '18 at 22:19

1 Answers1

1

Cannot reproduce the error myself. It's possible you don't have the purrr package loaded and so map is picking up a different function.

I would say that since your goal is to plot labels in geom_text, simply using st_centroid(ss_shape) would be the way to go. It would return your centroids as points which you can pass directly to geom_text:

eg)

ss_centroids <- st_centroid(ss_shape)
ggplot()+ 
  geom_text(data=ss_centroids,aes(x=X,y=Y,label=name))
Chris
  • 3,176
  • 1
  • 11
  • 29
  • I can't reproduce the poster's error, so unless you can I wouldn't jump to conclusions about what the problem is. WIthout library(purrr) I get "could not find function map". Not the poster's error.... – Spacedman Aug 23 '18 at 22:15
  • @Spacedman yes, you would get that error if you had no packages loaded with the 'map' function. It's possible he has another `map` function which is producing the error but as you point out, it is a guess - so I have edited the comment to make clear. The second point I made is the most important part of the answer anyhow. – Chris Aug 23 '18 at 23:17