Wednesday, 25 December 2019

r - fit two sf polygons seamlessly



Copied from my SO question




Suppose we have two shapefiles that should border seamlessly. Only, they don't. Is there a way to force them to stick to one another without gaps?


enter image description here






I have two shapefiles: one for European regions -- REG, the other for the neighbouring countries -- NEI. Both shapefiles are taken from Eurostat repository and should fit together nicely; but there are small gaps. Also, I need to simplify the polygons, and then the gaps become really notable.





I've tried several approaches but with no success. The only way to achieve the desired result that I see requires following steps:



  • create a line sf with just the border between my shapefiles;

  • from this line create a buffer polygon just big enough to cover all gaps;

  • join and dissolve this buffer to the shapefile for neighbours -- NEI;

  • clip off the expanded NEI with the REG shapefile.



Obviously, this is a rather clumsy workaround.


Is there a better way to go?








# install dev version of ggplot2
devtools::dev_mode()
devtools::install_github("tidyverse/ggplot2")


library(tidyverse)
library(sf)
library(rmapshaper)
library(ggthemes)


# load data
source(file = url("https://gist.githubusercontent.com/ikashnitsky/4b92f6b9f4bcbd8b2190fb0796fd1ec0/raw/1e281b7bb8ec74c9c9989fe50a87b6021ddbad03/minimal-data.R"))


# test how good they fit together
ggplot() +
geom_sf(data = REG, color = "black", size = .2, fill = NA) +
geom_sf(data = NEI, color = "red", size = .2, fill = NA)+
coord_sf(datum = NA)+
theme_map()

ggsave("test-1.pdf", width = 12, height = 10)

# simplify

REGs <- REG %>% ms_simplify(keep = .5, keep_shapes = TRUE)
NEIs <- NEI %>% ms_simplify(keep = .5, keep_shapes = TRUE)


ggplot() +
geom_sf(data = REGs, color = "black", size = .2, fill = NA) +
geom_sf(data = NEIs, color = "red", size = .2, fill = NA)+
coord_sf(datum = NA)+
theme_map()


ggsave("test-2.pdf", width = 12, height = 10)


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...