30 Day Map Challenge 2023

(Mostly) tmap vs ggplot2

David O’Sullivan

Overview

tmap and ggplot2: some background

A random walk through the maps

Reflections

tmap and ggplot2

ggplot2

Based on The Grammar of Graphics

Aesthetic ‘mappings’ between variables in data and visual variables

Focused on applying ‘geometries’—geom_point, geom_line, geom_bar, etc.—to data, e.g.

  ggplot(dataset) +
    geom_point(aes(x = var1, y = var2))

One geometry option is geom_sf for making maps

# read the data
ak <- st_read("../data/ak-city-demographics-2018.gpkg")
nz <- st_read("../data/nz.gpkg")

bb <- st_bbox(ak)

map1 <- ggplot(nz) + 
  geom_sf(lwd = 0) +
  geom_sf(data = ak, aes(fill = pop)) +
  scale_fill_distiller(palette = "Reds", name = "Population") +
  coord_sf(xlim = c(bb[1], bb[3]), ylim = c(bb[2], bb[4])) +
  theme(panel.background = element_rect(fill = "#bbeeff"))

map1

tmap

A ggplot2-like package tailored to thematic maps

In place of aes() to specify the data-visual variable relations, there are functions tm_polygons, tm_borders, tm_fill, tm_lines, and so on

Also provides tm_scalebar, tm_compass and other ‘map frills’

map2 <- tm_shape(nz, bbox = ak) +
  tm_fill() +
  tm_shape(ak) +
  tm_polygons(col = "pop", palette = "Reds", title = "Population") +
  tm_layout(bg.color = "#bbeeff", legend.outside = TRUE)

map2

ggplot2