How to create an sf point map using the layer function?

Hello ggplot2 and sf experts,

I am trying to use the layer function to create an sf map of points.

I know I could use geom_sf, but I have a reason why I want to use the layer function instead.

The code below works for the polygons, but not for the points..

Any ideas much appreciated

Thanks
David

library(tidyverse)
library(sf)
#> Linking to GEOS 3.11.2, GDAL 3.6.2, PROJ 9.2.0; sf_use_s2() is TRUE

nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"))
#> Reading layer `nc' from data source 
#>   `C:\Users\david\AppData\Local\R\win-library\4.3\sf\shape\nc.shp' 
#>   using driver `ESRI Shapefile'
#> Simple feature collection with 100 features and 14 fields
#> Geometry type: MULTIPOLYGON
#> Dimension:     XY
#> Bounding box:  xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965
#> Geodetic CRS:  NAD27

#this works
nc |>
  ggplot() +
  layer(
    geom = "sf",
    stat = "sf",
    position = "identity",
    mapping = aes(
      geometry = st_geometry(nc),
      fill = AREA
    )
  ) +
  coord_sf()


#this doesn't
nc2 <- nc |>
  sf::st_centroid() |>
  slice_head(n = 5)
#> Warning: st_centroid assumes attributes are constant over geometries

nc2 |>
  ggplot() +
  layer(
    geom = "sf",
    stat = "sf",
    position = "identity",
    mapping = aes(
      geometry = st_geometry(nc2),
      colour = NAME,
    )
  ) +
  coord_sf()
#> Error in if (type == "point") {: argument is of length zero

Created on 2023-12-14 with reprex v2.0.2

1 Like

Hi @davidhodge931

it seems that the layer_sf function does what you want if i correctly understand what you want to do.

I added the points to the polygons since otherwise it looks weird (but included the code anways for just the points).
Full Code:

library(tidyverse)
library(sf)

nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"))

nc2 <- nc |>
  sf::st_centroid() |>
  slice_head(n = 5)

# overlay points on layer map
nc |>
  ggplot() +
  layer(
    geom = "sf",
    stat = "sf",
    position = "identity",
    mapping = aes(
      geometry = st_geometry(nc),
      fill = AREA
    )
  ) +
  layer_sf(data = nc2,
    geom = "sf",
    stat = "sf",
    position = "identity",
    mapping = aes(
      geometry = st_geometry(nc2),
      colour = NAME
    )
  ) +
  coord_sf()

# only the points
nc2 |>
  ggplot() +
  layer_sf(
    geom = "sf",
    stat = "sf",
    position = "identity",
    mapping = aes(
      geometry = st_geometry(nc2),
      colour = NAME
    )
  ) +
  coord_sf()

Does this help?

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.