View source: R/stat-sf-coordinates.R
stat_sf_coordinates | R Documentation |
stat_sf_coordinates()
extracts the coordinates from 'sf' objects and
summarises them to one pair of coordinates (x and y) per geometry. This is
convenient when you draw an sf object as geoms like text and labels (so
geom_sf_text()
and geom_sf_label()
relies on this).
stat_sf_coordinates(
mapping = aes(),
data = NULL,
geom = "point",
position = "identity",
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE,
fun.geometry = NULL,
...
)
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
geom |
The geometric object to use to display the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
fun.geometry |
A function that takes a |
... |
Other arguments passed on to
|
coordinates of an sf
object can be retrieved by sf::st_coordinates()
.
But, we cannot simply use sf::st_coordinates()
because, whereas text and
labels require exactly one coordinate per geometry, it returns multiple ones
for a polygon or a line. Thus, these two steps are needed:
Choose one point per geometry by some function like sf::st_centroid()
or sf::st_point_on_surface()
.
Retrieve coordinates from the points by sf::st_coordinates()
.
For the first step, you can use an arbitrary function via fun.geometry
.
By default, function(x) sf::st_point_on_surface(sf::st_zm(x))
is used;
sf::st_point_on_surface()
seems more appropriate than sf::st_centroid()
since labels and text usually are intended to be put within the polygon or
the line. sf::st_zm()
is needed to drop Z and M dimension beforehand,
otherwise sf::st_point_on_surface()
may fail when the geometries have M
dimension.
These are calculated by the 'stat' part of layers and can be accessed with delayed evaluation.
after_stat(x)
X dimension of the simple feature.
after_stat(y)
Y dimension of the simple feature.
if (requireNamespace("sf", quietly = TRUE)) {
nc <- sf::st_read(system.file("shape/nc.shp", package="sf"))
ggplot(nc) +
stat_sf_coordinates()
ggplot(nc) +
geom_errorbarh(
aes(geometry = geometry,
xmin = after_stat(x) - 0.1,
xmax = after_stat(x) + 0.1,
y = after_stat(y),
height = 0.04),
stat = "sf_coordinates"
)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.