Is it possible to use `locator()` with plots generated by sf?

Viewed 46

I was wondering if it's possible to use the locator() function to create new points with plots generated by plot.sf. I'm sorry but I don't know how to create a reproducible example, so I will do my best to explain my problem.

When I run the following code (clicking, for example, on the centroid of some non-blue regions), the locator() returns the coordinates of the selected points. They have a reasonable value. However, when I plot them, the results are not that accurate (i.e. none of the chosen point lie in the selected region). Can you explain to me what's the problem?

library(sf)

nc = st_read(system.file("gpkg/nc.gpkg", package="sf"), quiet = TRUE)
plot(nc["SID74"], reset = FALSE)

pts <- locator()
pts <- st_sfc(st_multipoint(do.call(cbind, pts)), crs = st_crs(nc))
plot(pts, add = TRUE, pch = 16)
1 Answers

This is an interesting problem; I don't have an answer but I suspect that the issue will be environment related.

I ran your code on Linux (with a small adjustment for target number of points / clicks) and the code behaves as expected. I was able to place three points inside the Mecklenburg (as in Charlotte of Mecklenburg-Strelitz) county.

As locator() seems to use X11 (which is in my case native, but on Windows wrapped in a kind of convoluted fashion) I speculate that your problem may be environment related.

library(sf)

nc = st_read(system.file("gpkg/nc.gpkg", package="sf"), quiet = TRUE)
plot(nc["SID74"], reset = FALSE)

pts <- locator(n = 3) # to speed up the process
pts <- st_sfc(st_multipoint(do.call(cbind, pts)), crs = st_crs(nc))
plot(pts, add = TRUE, pch = 16)

map of NC with 3 points inside cnty Mecklenburg

Related