03 Polygons

A map with polygons.

Libraries

Code
library(sf)
library(tmap)
library(dplyr)
library(ggplot2)

Data wrangling

Code
nz <- st_read("data/nz.gpkg") %>%
  st_union() %>%
  st_as_sf() %>%
  mutate(What = "Land")

not_nz <- nz %>% 
  st_union() %>%
  st_buffer(500) %>%
  st_bbox() %>%
  st_as_sfc() %>%
  st_as_sf() %>%
  st_difference(nz) %>%
  mutate(What = "Water")

nz_not_nz <- nz %>%
  bind_rows(not_nz) %>%
  mutate(What = as.factor(What))

The maps

Perhaps unsurprisingly, this is the case where both packages require the least additional work to get the desired result.

tmap

tm_shape(nz_not_nz) + 
  tm_fill(
    fill = "What", 
    fill.scale = tm_scale_categorical(
      values = c("#33aa66", "#bbddff"))) +
  tm_layout(
    frame = FALSE,
    legend.frame = FALSE,
    legend.outside = TRUE)

ggplot2

ggplot(nz_not_nz) +
  geom_sf(aes(fill = What), linewidth = 0) +
  scale_fill_manual(values = c("#33aa66", "#bbddff")) +
  theme_void()