Philippe Massicotte
Philippe Massicotte

Reputation: 1529

How to place the geographical coordinates around polygon with sf?

I have this folowing polygon.

library(ggplot2)
library(sf)
#> Linking to GEOS 3.11.1, GDAL 3.6.2, PROJ 9.1.1; sf_use_s2() is TRUE

poly <- st_polygon(list(rbind(
  c(-90, 70),
  c(-40, 70),
  c(-40, 74),
  c(-90, 74),
  c(-90, 70)
))) |>
  st_sfc() |>
  st_segmentize(5) |>
  st_set_crs(4326) |>
  st_as_sf() |>
  st_transform(3413) |>
  st_cast("POLYGON")

ggplot() +
  geom_sf(data = poly) +
  theme(
    panel.background = element_blank()
  )

Is it possible to place the coordinate labels in a way that they would follow the “shape” of the polygon (instead of the plotting area)?

Created on 2023-01-11 with reprex v2.0.2

Upvotes: 3

Views: 103

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

This isn't natively possible with ggplot, but it is feasible to draw the axes in using geomtextpath:

library(geomtextpath)

xvals <- seq(-90, -40, 10)

yvals <- c(70, 72, 74)

xaxis <- lapply(xvals, function(x) {
  st_linestring(cbind(c(x - 5, x + 5), c(69, 69)))})|>
  st_sfc() |> 
  st_set_crs(4326) |>
  st_transform(crs = 3413) |>
  st_as_sf() |>
  within(label <- as.character(xvals))

yaxis <- lapply(yvals, function(x) {
  st_linestring(cbind(c(-93, -91), c(x, x)))})|>
  st_sfc() |> 
  st_set_crs(4326) |>
  st_transform(crs = 3413) |>
  st_as_sf() |>
  within(label <- as.character(yvals))

ggplot() +
  geom_sf(data = poly) +
  geom_textsf(data = xaxis, aes(label = label), linewidth = NA) +
  geom_textsf(data = yaxis, aes(label = label), linewidth = NA) +
  coord_sf(crs = 3413) +
  theme_void()

enter image description here

Upvotes: 5

Related Questions