Skip to content

Instantly share code, notes, and snippets.

@jamesgrecian
Created January 27, 2026 09:35
Show Gist options
  • Select an option

  • Save jamesgrecian/6bf9b3c3d7ea4e92fc10418aa3f0dc88 to your computer and use it in GitHub Desktop.

Select an option

Save jamesgrecian/6bf9b3c3d7ea4e92fc10418aa3f0dc88 to your computer and use it in GitHub Desktop.
Example script to map the Atlantic
#############################################
### Generate an enclosed map of the world ###
#############################################
# 2026-01-27
# example script for Marie
# this script creates a cookie cutter shape that overlays onto the map
# helps to make final figures look a little prettier by hiding distortion in basemaps
# load libraries
library(tidyverse)
library(rnaturalearth)
library(sf)
# Define a projection - in this case Lambert Azimuthal Equal Area centred on the mid Atlantic
prj = "+proj=laea +lat_0=10 +lon_0=-20 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"
# load a global shapefile
world_shp <- rnaturalearth::ne_countries(scale = 50, returnclass = "sf")
# define a box to clip shapefile to
# this will be the spatial extent of the plot
# make slightly bigger than required to avoid edge clip effects
CP <- sf::st_bbox(c(xmin = -85, xmax = 40, ymin = -80, ymax = 80)) |>
sf::st_as_sfc() |>
sf::st_segmentize(1) |>
st_set_crs(4326)
# crop the shapefile
world_shp <- world_shp |>
sf::st_crop(CP) |>
sf::st_buffer(0)
# project the clipping polygon
CP_prj <- CP |>
st_transform(crs = prj)
# get the bounding box in transformed coordinates and expand by 20%
xlim <- st_bbox(CP_prj)[c("xmin", "xmax")]*1.2
ylim <- st_bbox(CP_prj)[c("ymin", "ymax")]*1.2
# create an enclosing rectangle to overlay on the map using bbox
encl_rect <-
list(
cbind(
c(xlim[1], xlim[2], xlim[2], xlim[1], xlim[1]),
c(ylim[1], ylim[1], ylim[2], ylim[2], ylim[1])
)
) |>
st_polygon() |>
st_sfc(crs = prj)
# calcuate the difference between the enclosing rectangle and the CP outline
# this becomes the cookie cutter that you overlay on your map
cookie <- encl_rect |> st_difference(CP_prj)
# example plot
p1 <- ggplot() +
theme_void(base_size = 8) +
geom_sf(aes(), fill = "dark grey", colour = "dark grey", data = world_shp) +
geom_sf(aes(), fill = "white", color = "black", data = cookie, size = .5) +
coord_sf(xlim = c(-7000000, 7000000), ylim = c(-9750000, 8250000), crs = prj, expand = F)
p1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment