Skip to content

Instantly share code, notes, and snippets.

@ikashnitsky
Last active January 1, 2023 17:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikashnitsky/cf2c29a29d39f79bb1c857a4fefc2cd4 to your computer and use it in GitHub Desktop.
Save ikashnitsky/cf2c29a29d39f79bb1c857a4fefc2cd4 to your computer and use it in GitHub Desktop.
Give an example how and why to use line borders instead of polygons outlines in maps -- https://ikashnitsky.github.io/2023/map-borders
#===============================================================================
# 2020-04-08 -- twitter upd 2023-01-01 ik-q
# Showcase the map hack -- use border lines instead of polygon outlines
# https://twitter.com/ikashnitsky/status/1247875600305598464
# https://ikashnitsky.github.io/2023/map-borders
# Ilya Kashnitsky, ilya.kashnitsky@gmail.com
#===============================================================================
library(tidyverse)
library(sf)
set.seed(911)
# subset Greence, NUTS-3 regions
library(eurostat)
greece <- eurostat_geodata_60_2016 %>%
filter(LEVL_CODE==3,
str_sub(geo, 1, 2) == "EL") %>%
# create random values for filling the ploygons
mutate(random = runif(length(id))) %>%
select(id, geometry, random) %>%
st_transform(crs = 3035)
# plot with polygon outlines
greece %>%
ggplot()+
geom_sf(aes(fill = random), color = 2, size = 1)+
labs(title = "Polygons outlined")+
scale_fill_viridis_c(begin = .5)+
theme_map()+
theme(plot.background = element_rect(color = NA, fill = "#eeffff"))
gg_outline <- last_plot()
# produce border lines with rmapshaper::ms_innerlines()
library(rmapshaper)
bord <- greece %>% ms_innerlines()
# now plot without polygon outlines and with borders as lines
greece %>%
ggplot()+
geom_sf(aes(fill = random), color = NA)+
geom_sf(data = bord, color = 2, size = 1)+
labs(title = "Borders as lines")+
scale_fill_viridis_c(begin = .5)+
theme_map()+
theme(plot.background = element_rect(color = NA, fill = "#eeffff"))
gg_bord <- last_plot()
# put side by side
library(patchwork)
(
gg_outline + gg_bord
) +
plot_layout(guides = "collect")+
plot_annotation(
caption = "! Look at the islands",
theme = theme(plot.background = element_rect(color = NA, fill = "#eeffff"))
)
ggsave("out.png", width = 6, height = 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment