Code
library(sf)
library(ggplot2)
library(cols4all)
library(dplyr)
<- st_read("some-polygons.gpkg") polygons
Here is how slivers and gaps can happen…
Read in some polygons.
Simplify them without due care and attention, and voila!
all_polys_1 <- bind_rows(
polygons |>
mutate(source = "Source polygons"),
polygons |>
st_simplify(dTolerance = 100) |>
mutate(source = "Source polygons simplified")
)
ggplot(all_polys_1) +
geom_sf(aes(fill = name), alpha = 0.35, lwd = 0) +
scale_fill_discrete_c4a_cat(palette = "palette36") +
guides(fill = "none") +
facet_wrap( ~ source) +
theme_void() +
theme(
strip.text = element_text(size = 16,
margin = margin(3, 0, 3, 0, "pt")))
By contrast if we use the simplification function from rmapshaper
topology is preserved, even with pretty dramatic simplification (here retaining only 25% of polygon vertices.)
library(rmapshaper)
all_polys_2 <- bind_rows(
polygons |>
mutate(source = "Source polygons"),
polygons |>
ms_simplify(keep = 0.25) |>
mutate(source = "Topology preserved")
)
ggplot(all_polys_2) +
geom_sf(aes(fill = name), alpha = 0.35, lwd = 0) +
scale_fill_discrete_c4a_cat(palette = "palette36") +
guides(fill = "none") +
facet_wrap( ~ source) +
theme_void() +
theme(
strip.text = element_text(size = 16,
margin = margin(3, 0, 3, 0, "pt")))
The rmapshaper::topojson_write
function also allows you to write your polygons out to the topology preserving TopoJSON format.
rmapshaper
is associated with the excellent MapShaper tool.
# License (MIT)
#
# Copyright (c) 2023 David O'Sullivan
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
© 2023-24 David O’Sullivan