Skip to content

Instantly share code, notes, and snippets.

@eliocamp
Created November 9, 2023 15:12
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 eliocamp/19197585af32c1123b21ba39cec8a016 to your computer and use it in GitHub Desktop.
Save eliocamp/19197585af32c1123b21ba39cec8a016 to your computer and use it in GitHub Desktop.
Hex country density
library(ggplot2)
library(units)
library(sf)
world <- rnaturalearth::ne_countries(returnclass = "sf", scale = 10) |>
st_transform(crs = "+proj=moll")
# Make a hexagonal grid
size <- 1000000
units(size) <- as_units("km^2")
grid <- st_make_grid(world, cellsize = size, square = FALSE)
# Remove hexagons that fall outside the world
outside <- grid |>
st_centroid() |>
st_transform(crs = "+proj=lonlat") |>
st_is_empty()
grid <- grid[!outside]
# Compute number of countries tha fall within each hex
n_country <- st_intersects(grid, world) |>
lengths()
# Sort in ascending order so darker hex get drawn last.
# Otherwise the perimeter of dark hexes gets obscured by
# the perimeter of lighter hexes.
o <- order(n_country)
grid <- grid[o]
n_country <- n_country[o]
ggplot() +
geom_sf(data = grid,
aes(fill = cut_width(n_country, 1, boundary = 0),
color = after_scale(colorspace::darken(fill, 0.2))),
linewidth = 0.5) +
geom_sf(data = world, fill = NA, linewidth = 0.1, color = alpha("black", .3)) +
scale_fill_continuous(name = NULL, super = metR::ScaleDiscretised,
low = "white", high = "#de3e80",
guide = guide_colorsteps(barwidth = 20,
barheight = 0.4,
show.limits = TRUE, frame.colour = "black")) +
theme_void(base_size = 16) +
theme(legend.position = "bottom") +
labs(title = "Countries per 1 million squared kilometre")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment