Skip to content
Invisible link to canonical for Microformats World map represented by cyan dots on a dark gray background.

Beautiful maps with R (I): Fishnets, honeycombs and pixels

Simplified maps with R



Update (25 November 2026)

The maps now use ggplot2, with a final comparison of the five grid methods alongside the original boundaries.

Sometimes you want to produce maps with special layouts. I especially like maps with modified geometries, e.g. simplifying the original shapes to squares or dots. When searching the web, I found the fantastic post Fishnets and Honeycomb: Square vs. Hexagonal Spatial Grids by Matt Strimas-Mackey, which was a huge inspiration (by the way, don’t miss his blog, full of very interesting pieces of work).

The only thing I was not completely comfortable with was that the post used the old-fashioned sp package instead of my personal favorite, the sf package. The post was published in 2016, and note that the author has also moved to the sf package since then. So I decided to explore further options with sf.

The approach is similar, using grids over a map and working with them, but with st_make_grid(). I also expanded it by grouping the grids and producing dots over the geometries. So basically I produced five variations of the map:

Type Replacement Grouped
Fishnet Square No
Puzzle Square Yes
Honeycomb Hexagon No
Hexbin Hexagon Yes
Pixel Dot No

This technique works best with less detailed, simplified geometries.

Required R packagesPermalink to Required R packages

library(sf)
library(giscoR)
library(dplyr)
library(ggplot2)
library(stringr)

# Define a common theme for the maps.
background <- "#FAF8F2"
foreground <- "#203B47"

map_title <- "inter-tight"
map_regular <- "inter"

sysfonts::font_add_google("Inter Tight", family = map_title)
sysfonts::font_add_google("Inter", family = map_regular)
showtext::showtext_opts(dpi = knitr::opts_chunk$get("dpi"))
showtext::showtext_auto()

sysfonts::font_add_google("Inter Tight", family = map_title)
sysfonts::font_add_google("Inter", family = map_regular)
showtext::showtext_opts(dpi = knitr::opts_chunk$get("dpi"))
showtext::showtext_auto()

theme_set(
  theme_grey(paper = background, base_family = map_regular, ink = foreground) +
    theme(
      plot.title = element_text(family = map_title, face = "bold"),
      legend.title = element_text(family = map_title, face = "bold"),
      panel.background = element_rect(fill = background),
      panel.grid = element_blank(),
      axis.text = element_blank(),
      axis.ticks = element_blank(),
      strip.background = element_rect(fill = background),
      strip.text = element_text(family = map_title, face = "bold"),
      strip.clip = "off",
      plot.margin = margin(10, 10, 10, 10)
    )
)

Working with square gridsPermalink to Working with square grids

Let’s use the square option of st_make_grid() and play a bit with it.

uk <- gisco_get_nuts(
  year = 2021, country = "GBR", nuts_level = 1, epsg = 3857,
  resolution = 20
) %>%
  # # Group by nation
  mutate(NAME_EN = case_when(
    str_detect(NUTS_NAME, "Wales|Scotland|Ireland") ~ NUTS_NAME,
    TRUE ~ "England"
  )) %>%
  group_by(NAME_EN) %>%
  summarise(do_union = TRUE) %>%
  # Iteration using indexes
  mutate(index_target = row_number())

uk_palette <- c(
  England = "#A33C45",
  Scotland = "#345F91",
  Wales = "#477C54",
  "Northern Ireland" = "#A7A6D5"
)

The cellsize should be set in the same unit as the projection (in this case, meters). Smaller cells create denser grids and can use substantially more memory.

# Grid to sf
grid <- uk %>%
  st_make_grid(50 * 1000,
    # Kms
    crs = st_crs(uk),
    what = "polygons",
    square = TRUE
  ) %>%
  st_as_sf() %>%
  mutate(index = row_number())

# We identify the grids that belong to an entity by assessing the centroid
cent_merge <- grid %>%
  st_centroid() %>%
  st_filter(uk) %>%
  st_join(uk)

grid_new <- grid %>% inner_join(st_drop_geometry(cent_merge), by = "index")

# Fishnet
fish_geom <- grid_new %>%
  group_by(NAME_EN) %>%
  summarise(do_union = FALSE)


# Now let's create the puzzle
puzzle_geom <- grid_new %>%
  # Avoid slivers
  st_buffer(0.5) %>%
  group_by(NAME_EN) %>%
  summarise(do_union = TRUE) # The only difference is do_union

# Plot

fish_geom %>%
  mutate(label = "Fishnet") %>%
  bind_rows(
    puzzle_geom %>%
      mutate(label = "Puzzle")
  ) %>%
  mutate(label = forcats::fct_inorder(label)) %>%
  ggplot() +
  geom_sf(
    aes(fill = NAME_EN),
    colour = background,
    linewidth = 0.2,
    show.legend = FALSE
  ) +
  facet_wrap(~label) +
  scale_fill_manual(values = uk_palette) +
  theme(
    strip.text = element_text(
      size = rel(1.2), hjust = 0, vjust = 1,
      margin = margin(b = 10)
    )
  )

Two maps of the United Kingdom comparing separate square cells with cells merged into regional shapes. Colors distinguish regions.

Going hexPermalink to Going hex

Extremely easy. We just need to change the square parameter of st_make_grid() from TRUE to FALSE.

# Grid to sf
grid_hex <- uk %>%
  st_make_grid(50 * 1000,
    # Kms
    crs = st_crs(uk),
    what = "polygons",
    square = FALSE # This is the only piece that changes!!!
  ) %>%
  st_as_sf() %>%
  mutate(index = row_number())

cent_merge_hex <- grid_hex %>%
  st_centroid() %>%
  st_filter(uk) %>%
  st_join(uk)

grid_hex_new <- grid_hex %>%
  inner_join(st_drop_geometry(cent_merge_hex), by = "index")

# Honeycomb
honey_geom <- grid_hex_new %>%
  group_by(NAME_EN) %>%
  summarise(do_union = FALSE)


# Now let's create the hexbin
hexbin_geom <- grid_hex_new %>%
  # Avoid slivers
  st_buffer(0.5) %>%
  group_by(NAME_EN) %>%
  summarise(do_union = TRUE) # The only difference is do_union

# Plot

honey_geom %>%
  mutate(label = "Honeycomb") %>%
  bind_rows(
    hexbin_geom %>%
      mutate(label = "Hexbin")
  ) %>%
  mutate(label = forcats::fct_inorder(label)) %>%
  ggplot() +
  geom_sf(
    aes(fill = NAME_EN),
    colour = background,
    linewidth = 0.2,
    show.legend = FALSE
  ) +
  facet_wrap(~label) +
  scale_fill_manual(values = uk_palette) +
  theme(
    strip.text = element_text(
      size = rel(1.2), hjust = 0, vjust = 1,
      margin = margin(b = 10)
    )
  )

Two maps of the United Kingdom comparing separate hexagonal cells with cells merged into regional shapes. Colors distinguish regions.

Pixel it!Permalink to Pixel it!

For the dot map, use the centers of a hexagonal grid. Assign each center to a region, then draw a circle with a radius set to 40% of the grid cell size.

grid_pixels <- uk %>%
  st_make_grid(50 * 1000,
    # Kms
    crs = st_crs(uk),
    what = "centers",
    square = FALSE
  ) %>%
  st_as_sf() %>%
  mutate(index = row_number())

pixels_geom <- grid_pixels %>%
  st_join(uk, left = FALSE) %>%
  # We need to buffer the points to get polygons, based on the grid resolution
  st_buffer(50 * 1000 * 0.4) %>%
  group_by(NAME_EN) %>%
  summarise(do_union = FALSE)


# Plot
ggplot(pixels_geom) +
  geom_sf(
    aes(fill = NAME_EN),
    colour = background,
    linewidth = 0.2,
    show.legend = FALSE
  ) +
  scale_fill_manual(values = uk_palette) +
  labs(title = "Pixel")

Map of the United Kingdom made of round dots, with color distinguishing the four constituent countries.

Wrap upPermalink to Wrap up

Finally, I wrapped all that in stdh_gridpol().

stdh_gridpol <- function(sf,
                         to = "fishnet",
                         gridsize = as.integer(
                           min(
                             diff(st_bbox(sf)[c(1, 3)]),
                             diff(st_bbox(sf)[c(2, 4)])
                           ) / 40
                         ),
                         sliver = 0.5) {
  if (!all(st_geometry_type(sf) %in% c("POLYGON", "MULTIPOLYGON"))) {
    stop("Input should be MULTIPOLYGON or POLYGON")
  }
  if (!to %in% c("fishnet", "puzzle", "honeycomb", "hexbin", "pixel")) {
    stop("'to' should be 'fishnet','puzzle','honeycomb','hexbin' or 'pixel'")
  }

  if (inherits(sf, "sf")) {
    initial <- sf
    initial$index_target <- 1:nrow(initial)
  } else {
    initial <- st_sf(index_target = 1:length(sf), geom = sf)
  }

  target <- st_geometry(initial)

  if (to %in% c("fishnet", "puzzle")) {
    sq <- T
  } else {
    sq <- F
  }
  if (to == "pixel") {
    grid <- st_make_grid(target,
      gridsize,
      crs = st_crs(initial),
      what = "centers",
      square = FALSE
    )
  } else {
    grid <- st_make_grid(
      target,
      gridsize,
      crs = st_crs(initial),
      what = "polygons",
      square = sq
    )
  }
  grid <- st_sf(index = 1:length(lengths(grid)), grid) # Add index
  if (to == "pixel") {
    cent_merge <- st_join(grid, initial["index_target"], left = F)
    grid_new <- st_buffer(cent_merge, gridsize * 0.4)
  } else {
    cent_grid <- st_centroid(grid)
    cent_merge <- st_join(cent_grid, initial["index_target"], left = F)
    grid_new <- inner_join(grid, st_drop_geometry(cent_merge), by = "index")
  }
  if (to %in% c("fishnet", "honeycomb", "pixel")) {
    geom <- aggregate(
      grid_new,
      by = list(grid_new$index_target),
      FUN = min,
      do_union = FALSE
    )
  } else {
    geom <- aggregate(
      st_buffer(grid_new, sliver),
      by = list(grid_new$index_target),
      FUN = min,
      do_union = TRUE
    )
  }
  if (inherits(sf, "sf")) {
    fin <- left_join(
      geom %>% select(index_target),
      st_drop_geometry(initial),
      by = "index_target"
    ) %>%
      select(-index_target)
    fin <- st_cast(fin, "MULTIPOLYGON")
    return(fin)
  } else {
    fin <- st_cast(geom, "MULTIPOLYGON")
    return(st_geometry(fin))
  }
}
# End of the function-----

fish <- stdh_gridpol(uk, to = "fishnet", gridsize = 50 * 1000)
puzz <- stdh_gridpol(uk, to = "puzzle", gridsize = 50 * 1000)
hon <- stdh_gridpol(uk, to = "honeycomb", gridsize = 50 * 1000)
hex <- stdh_gridpol(uk, to = "hexbin", gridsize = 50 * 1000)
pix <- stdh_gridpol(uk, to = "pixel", gridsize = 50 * 1000)
grid_maps <- bind_rows(
  list(
    Map = uk,
    Fishnet = fish,
    Puzzle = puzz,
    Honeycomb = hon,
    Hexbin = hex,
    Pixel = pix
  ),
  .id = "method"
) %>%
  mutate(
    method = factor(
      method,
      levels = c("Map", "Fishnet", "Puzzle", "Honeycomb", "Hexbin", "Pixel")
    )
  )

ggplot(grid_maps) +
  geom_sf(
    aes(fill = NAME_EN),
    colour = background,
    linewidth = 0.2,
    show.legend = FALSE
  ) +
  scale_fill_manual(values = uk_palette) +
  facet_wrap(vars(method), nrow = 2) +
  labs(
    title = "Redrawing the United Kingdom",
    subtitle = "Original boundaries and five representations on a 50 km grid"
  )

Six maps of the United Kingdom compare the original boundaries with square cells, merged squares, hexagonal cells, merged hexagons and dots.

And that’s it! The function stdh_gridpol() has some alert mechanisms, such as accepting only POLYGON or MULTIPOLYGON, and the default value of gridsize is computed so that the shortest dimension has 40 cells.

ReferencesPermalink to References

How to cite this post

For attribution, please cite this work as:

Hernangómez, D. (2019, June 2). Beautiful maps with R (I): Fishnets, honeycombs and pixels. One World. https://dieghernan.github.io/201906_Beautiful1/

BibTeX
@misc{post20190602-beautiful1,
  author = {Hernangómez, Diego},
  title = {Beautiful maps with R (I): Fishnets, honeycombs and pixels},
  year = {2019},
  month = jun,
  howpublished = {One World},
  url = {https://dieghernan.github.io/201906_Beautiful1/},
}

Mentions and replies

Conversations from across the web.

Shared your thoughts on this post? Drop your link here!

Publish a page that links to this post, then submit its URL. Webmention.io will check the link before the mention appears.


Related posts