Skip to content

Instantly share code, notes, and snippets.

@jlacko
Forked from DavZim/map_projections.R
Last active March 23, 2021 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlacko/9262028eaaf48a0e4b7e3e309f118816 to your computer and use it in GitHub Desktop.
Save jlacko/9262028eaaf48a0e4b7e3e309f118816 to your computer and use it in GitHub Desktop.
Creates a gif of the world in different map projections
library(tidyverse)
library(sf)
library(giscoR)
library(gganimate)
# world, with Greenland and Congo (roughly equal in area) in red
world <- gisco_get_countries(resolution = "20") %>%
mutate(color = ifelse(CNTR_ID %in% c('GL', 'CD'), 'red', 'black')) %>%
group_by(color) %>%
summarise() %>%
st_cast("MULTIPOLYGON")
# see also: https://proj.org/operations/projections/index.html
projs <- list(
"Mercator" = "+proj=merc",
"WGS 84" = "+proj=longlat",
"Robinson" = "+proj=robin",
"Compact Miller" = "+proj=comill",
"Eckert I" = "+proj=eck1",
"Eckert II" = "+proj=eck2",
"Eckert III" = "+proj=eck3",
"Eckert IV" = "+proj=eck4",
"Mollweide" = "+proj=moll",
"Azimuth Equidistant" = "+proj=aeqd",
"Lambert Equal Area" = "+proj=laea",
"Adams World in a Square 2" = "+proj=adams_ws2",
"Sinusoidal (Sanson-Flamsteed)" = "+proj=sinu",
"Interrupted Goode Homolosine" = "+proj=igh"
)
dd <- map_dfr(projs, function(p) {
d <- world %>%
st_transform(p)
dd <- rbind(st_coordinates(d[d$color == 'red', ]) %>%
as_tibble() %>%
mutate(color = 'red'),
st_coordinates(d[d$color == 'black', ]) %>%
as_tibble() %>%
mutate(color = 'black'))
res <- dd %>%
select(x = X, y = Y, everything()) %>%
mutate(id = paste0(L1, L2, L3)) %>%
mutate(x_orig = x, y_orig = y, projection = p,
x = (x - min(x)) / (max(x) - min(x)),
y = (y - min(y)) / (max(y) - min(y)))
res
}) %>%
mutate(projection = factor(projection, levels = unlist(projs)))
anim <- ggplot(dd, aes(x = x,
y = y,
group = id,
fill = color)) +
geom_polygon(color = NA) +
transition_states(projection) +
ease_aes("cubic-in-out") +
labs(title = "The World in '{names(projs)[projs == closest_state]}' projection",
subtitle = "Projection: '{closest_state}'") +
scale_fill_identity(c('black' = 'black',
'red' = 'red')) +
theme_minimal() +
theme(axis.title=element_blank(),
axis.text=element_blank(),
axis.ticks=element_blank(),
panel.grid=element_blank(),
plot.background=element_rect(fill = "white"))
anim_save("./img/projections.gif", anim, res = 200, width = 1200, height = 675)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment