Skip to content

Instantly share code, notes, and snippets.

@obrl-soil
Created September 28, 2025 02:33
Show Gist options
  • Select an option

  • Save obrl-soil/9959a0c159c410bb255c4dcb234316d2 to your computer and use it in GitHub Desktop.

Select an option

Save obrl-soil/9959a0c159c410bb255c4dcb234316d2 to your computer and use it in GitHub Desktop.
Some options for plotting H3 cells on a global scale
library(ggplot2)
library(h3jsr)
library(sf)
library(rnaturalearth)
# world data
world <- rnaturalearth::ne_countries(scale = 'small', returnclass = 'sf') |>
# needs a l'il clean
st_make_valid()
# h3 grids
all_cells <- h3jsr::get_res0()
children <- h3jsr::get_children(
h3_address = all_cells, res = 1, simple = TRUE)
base_grid <- h3jsr::cell_to_polygon(input = children, simple = FALSE) |>
st_as_sf()
# Orthographic projection
# Center longitude on 0
world1 <- sf::st_transform(x = world, crs = "+proj=ortho +lat_0=0 +lon_0=0") |>
st_make_valid()
# For some reason, can not center longitude on 180 (use 179 for now)
world2 <- sf::st_transform(x = world, crs = "+proj=ortho +lat_0=0 +lon_0=179") |>
st_make_valid()
# Crop into two hemispheres
# Wrap prime meridian
grid1 <- st_crop(base_grid, xmin = -90, xmax = 90, ymin = -90, ymax = 90)
# Wrap anti-meridian
grid2 <- st_crop(base_grid, xmin = 90, xmax = -90, ymin = -90, ymax = 90)
# Orthographic projection
grid1 <- sf::st_transform(x = grid1, crs = "+proj=ortho +lat_0=0 +lon_0=0") |>
st_make_valid()
grid2 <- sf::st_transform(x = grid2, crs = "+proj=ortho +lat_0=0 +lon_0=180") |>
st_make_valid()
# Plot
par(mfrow=c(1,2))
plot(world1$geometry, col = "orange", lty = 0)
plot(grid1$geometry, add = TRUE)
plot(world2$geometry, col = "orange", lty = 0)
plot(grid2$geometry, add = TRUE, fill = NA)
# ggplot2 approach
library(patchwork)
map1 <- ggplot(grid1) +
geom_sf(data = world1, fill = 'orange', colour = NA) +
geom_sf(fill = NA) +
theme_void() +
coord_sf()
map2 <- ggplot(grid2) +
geom_sf(data = world2, fill = 'orange', colour = NA) +
geom_sf(fill = NA) +
theme_void() +
coord_sf()
map1 + map2
# per https://github.com/obrl-soil/h3jsr/issues/14,
# plot a cell near the poles using antarctic polar projection EPSG 3031
cell <- h3jsr::cell_to_polygon("81f17ffffffffff")
cell2 <- sf::st_transform(x = cell, crs = 3031) |>
st_as_sf()
# need to at least trim supporting data back to the equator:
base_south <- base_grid |>
cbind(st_coordinates(st_centroid(base_grid))) |>
dplyr::filter(Y < 0) |>
st_transform(3031)
world_south <- st_transform(world, 3031) |>
st_make_valid() |>
st_intersection(base_south)
ggplot() +
geom_sf(data = world_south, fill = 'orange', colour = NA) +
geom_sf(data = base_south, fill = NA) +
geom_sf(data = cell2, fill = 'red') +
theme_void() +
coord_sf()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment