Closed
Description
According to #2111, ggplot2 decided not to implement stat_sf(geom = "text")
to avoid complexity.
But, I face the necessity to plot labels and texts on sf maps so often that I'm urged to make a package...
IIUC, it's not so complicated to implement a stat that retrieves the coordinates from a sf object and map the computed variables X
and Y
. Do you feel it's ok for this to live in ggplot2? If yes, I'm happy to make a PR. (If no, I will develop my package and submit it to CRAN.)
Here's an example implementation:
library(ggplot2)
StatSfCoordinates <- ggproto(
"StatSfCoordinates", Stat,
setup_params = function(data, params) {
if (is.null(params$fun.geometry)) {
params$fun.geometry <- sf::st_point_on_surface
}
params
},
compute_group = function(data, scales, fun.geometry) {
points_sfc <- fun.geometry(data$geometry)
coordinates <- sf::st_coordinates(points_sfc)
data <- cbind(data, coordinates)
data
},
default_aes = aes(x = stat(X), y = stat(Y)),
required_aes = c("geometry")
)
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
ggplot(nc[1:3, ]) +
geom_sf(aes(fill = AREA)) +
geom_label(aes(geometry = geometry, label = NAME), stat = "sf_coordinates")
#> Warning in st_point_on_surface.sfc(data$geometry): st_point_on_surface may
#> not give correct results for longitude/latitude data
Created on 2018-07-08 by the reprex package (v0.2.0).
Metadata
Metadata
Assignees
Labels
No labels