Skip to content

Instantly share code, notes, and snippets.

@marcosci
Created December 1, 2022 10:10
Show Gist options
  • Save marcosci/0e8f468bc13620fcc3a58eac4dba9821 to your computer and use it in GitHub Desktop.
Save marcosci/0e8f468bc13620fcc3a58eac4dba9821 to your computer and use it in GitHub Desktop.
library(sf)
library(rnaturalearth)
library(tidyverse)
library(ggtext)
sf_use_s2(FALSE)
tmp_dr <- tempdir()
tmp_fl <- tempfile()
download.file("https://geodata.ucdavis.edu/gadm/gadm4.1/json/gadm41_FRA_4.json.zip", tmp_fl)
tmp_fl_name <- unzip(tmp_fl, exdir = tmp_dr, list = TRUE)$Name
unzip(tmp_fl, exdir = tmp_dr)
country <- st_read(paste0(tmp_dr, "/", tmp_fl_name))|>
st_make_valid()
country_centroids <- country |>
st_centroid()
china <- ne_countries(country = "China", returnclass = "sf") |>
st_make_valid() |>
st_centroid()
usa <- ne_countries(country = "United States of America", returnclass = "sf") |>
st_make_valid() |>
st_centroid()
country_centroids <- st_transform(country_centroids, crs = st_crs(china))
distance_us <- st_distance(country_centroids, usa)
country_centroids$distance_us <- distance_us
distance_china <- st_distance(country_centroids, china)
country_centroids$distance_china <- distance_china
country$color_flag <- country_centroids |>
mutate(color_flag = case_when(
distance_china > distance_us ~ 0,
TRUE ~ 1
),
color_flag = factor(color_flag)) |>
pull(color_flag)
mean_x <- country |>
st_cast("MULTIPOLYGON") |>
st_coordinates() |>
as_tibble() |>
pull(X) |>
mean()
mean_y <- country |>
st_cast("MULTIPOLYGON") |>
st_coordinates() |>
as_tibble() |>
pull(Y) |>
mean()
ggplot(country) +
geom_sf(aes(fill = color_flag), color = alpha("white", 0.3), size = 0.3) +
scale_fill_manual(values = c("#A1BECE", "#FF9799")) +
guides(fill = "none", color = "none") +
annotate("rect", xmin = mean_x - 6.1, xmax = mean_x - 4.9, ymin = mean_y + 3.6, ymax = mean_y + 3.8, color = NA, fill = "#A1BECE", alpha = .6) +
annotate(geom='richtext', x = mean_x - 5.5, y = mean_y + 4, label = "Closer to <br> __US__", label.size = 0, size = 11, fill = NA, family="Iosevka") +
annotate("rect", xmin = mean_x + 5.6, xmax = mean_x + 7.4, ymin = mean_y - 1.4, ymax = mean_y - 1.2, color = NA, fill = "#FF9799", alpha = .6) +
annotate(geom='richtext', x = mean_x + 6.5, y = mean_y - 1, label = "Closer to <br> __China__", label.size = 0, size = 11, fill = NA, family="Iosevka") +
# coord_cartesian(clip = "off") +
theme_void()
ggsave("france.png", width = 12, height = 12, dpi = 600)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment