1context("stat_sf_coordinates")
2
3comp_sf_coord <- function(df, ...) {
4  plot <- ggplot(df) + stat_sf_coordinates(...)
5  layer_data(plot)
6}
7
8test_that("stat_sf_coordinates() retrieves coordinates from sf objects", {
9  skip_if_not_installed("sf")
10
11  # point
12  df_point <- sf::st_sf(geometry = sf::st_sfc(sf::st_point(c(0, 0))))
13  expect_identical(comp_sf_coord(df_point)[, c("x", "y")], data_frame(x = 0, y = 0))
14
15  # line
16  c_line <- rbind(c(-1, -1), c(1, 1))
17  df_line <- sf::st_sf(geometry = sf::st_sfc(sf::st_linestring(c_line)))
18  expect_identical(
19    # Note that st_point_on_surface() does not return the centroid for
20    # `df_line`, which may be a bit confusing. So, use st_centroid() here.
21    comp_sf_coord(df_line, fun.geometry = sf::st_centroid)[, c("x", "y")],
22    data_frame(x = 0, y = 0)
23  )
24
25  # polygon
26  c_polygon <- list(rbind(c(-1, -1), c(-1, 1), c(1, 1), c(1, -1), c(-1, -1)))
27  df_polygon <- sf::st_sf(geometry = sf::st_sfc(sf::st_polygon(c_polygon)))
28  expect_identical(comp_sf_coord(df_point)[, c("x", "y")], data_frame(x = 0, y = 0))
29
30  # computed variables (x and y)
31  df_point <- sf::st_sf(geometry = sf::st_sfc(sf::st_point(c(1, 2))))
32  expect_identical(
33    comp_sf_coord(df_point, aes(x = stat(x) + 10, y = stat(y) * 10))[, c("x", "y")],
34    data_frame(x = 11, y = 20)
35  )
36})
37
38test_that("stat_sf_coordinates() ignores Z and M coordinates", {
39  skip_if_not_installed("sf")
40
41  # XYM
42  c_polygon <- list(rbind(c(-1, -1, 0), c(-1, 1, 0), c(1, 1, 0), c(1, -1, 0), c(-1, -1, 0)))
43  df_xym <- sf::st_sf(geometry = sf::st_sfc(sf::st_polygon(c_polygon, dim = "XYM")))
44  # Note that st_centroid() and st_point_on_surface() cannot handle M dimension since
45  # GEOS does not support it. The default fun.geometry should drop M.
46  expect_identical(comp_sf_coord(df_xym)[, c("x", "y")], data_frame(x = 0, y = 0))
47})
48