Key Learnings from, and Solutions to the exercises in Chapter 8 of the book Geocomputation with R by Robin Lovelace, Jakub Nowosad and Jannes Muenchow.
Geocomputation with R
Textbook Solutions
Author
Aditya Dahiya
Published
March 2, 2025
In this chapter, I use {tmap} (Tennekes 2018a), but I also use {ggplot2}(Wickham 2016) to produce equivalent maps, as produced by {tmap}(Tennekes 2018b) in the textbook. In addition, I use {cols4all}(Tennekes and Puts 2023) palettes for colour and fill scales.
Using pacman for quick loading and updating of packages.
Code
pacman::p_load( sf, # Simple Features in R terra, # Handling rasters in R tidyterra, # For plotting rasters in ggplot2 tidyverse, # All things tidy; Data Wrangling magrittr, # Using pipes with raster objects spData, # Spatial Datasets spDataLarge, # Large Spatial Datasets patchwork, # Composing plots gt, # Display GT tables with R tmap, # Using {tmap} for maps cols4all # Colour Palettes)# nz_elev = rast(system.file("raster/nz_elev.tif", package = "spDataLarge"))# install.packages("spDataLarge", repos = "https://geocompr.r-universe.dev")
9.1 Introduction
Cartography is a crucial aspect of geographic research, blending communication, detail, and creativity.
Static maps in R can be created using the plot() function, but advanced cartography benefits from dedicated packages.
The chapter focuses in-depth on the tmap package rather than multiple tools superficially.
Some example colour palettes to use in maps is shown below in Table 1.
Grammar of graphics: Like ggplot2, tmap follows a structured approach, separating input data from aesthetics (visual properties). Example, shown in Figure 1 .
Basic structure: Uses tm_shape() to define the input dataset (vector or raster), followed by layer elements like tm_fill() and tm_borders().
Layering approach:
tm_fill(): Fills (multi)polygon areas.
tm_borders(): Adds border outlines to (multi)polygons.
tm_polygons(): Combines fill and border.
tm_lines(): Draws lines for (multi)linestrings.
tm_symbols(): Adds symbols for points, lines, and polygons.
tm_raster(): Displays raster data.
tm_rgb(): Handles multi-layer rasters.
tm_text(): Adds text labels.
Layering operator: The + operator is used to add multiple layers.
Quick maps: qtm() provides a fast way to generate thematic maps (qtm(nz) ≈ tm_shape(nz) + tm_fill() + tm_borders()).
Limitations of qtm(): Less control over aesthetics, so not covered in detail in this chapter.
fill_alpha, col_alpha: Transparency for fill and border.
Applying aesthetics:
Use a column name to map a variable. Pass a character string referring to a column name.
Use a fixed value for constant aesthetics.
Additional arguments for visual variables:
.scale: Controls representation on the map and legend.
.legend: Customizes legend settings.
.free: Defines whether each facet uses the same or different scales.
Code
g1 <-ggplot() +geom_sf(data = nz,mapping =aes(fill = Land_area),colour ="transparent" ) +scale_fill_stepsn(colors =c4a(palette ="brewer.blues", type ="seq"),name ="Land Area" ) + ggthemes::theme_map() +theme(legend.position ="inside",legend.position.inside =c(0.9, 0.1),legend.justification =c(1, 0),panel.background =element_rect() )g2 <-ggplot() +geom_sf(data = nz,mapping =aes(fill = Land_area),colour ="black" ) + ggthemes::theme_map() +theme(legend.position ="inside",legend.position.inside =c(0.9, 0.1),legend.justification =c(1, 0),panel.background =element_rect() ) +scale_fill_viridis_b(option ="C")# If we want to replicate the {tmap} style bin labels, wiht {ggplot2},# some manual code in required (Credits: Grok3)# Load the New Zealand datanz <- spData::nz# Define bin widthbin_width <-10000# Determine breaks based on the data rangebreaks <-seq(from =floor(min(nz$Land_area) / bin_width) * bin_width, to =ceiling(max(nz$Land_area) / bin_width) * bin_width, by = bin_width )# Create labels for the binslabels <-paste0(format(breaks[-length(breaks)], big.mark =","), " - ", format(breaks[-1] -1, big.mark =",") )# Bin the land area datanz <- nz |>mutate(binned_land_area =cut( nz$Land_area, breaks = breaks, labels = labels, include.lowest =TRUE ) )# Generate colors for the binsn_bins <-length(levels(nz$binned_land_area))mypal <- cols4all::c4a(palette ="brewer.blues", n = n_bins)g3 <-ggplot() +geom_sf(data = nz,mapping =aes(fill = binned_land_area),colour ="transparent" ) +scale_fill_manual(values = mypal,name ="Land Area" ) + ggthemes::theme_map() +theme(legend.position ="inside",legend.position.inside =c(0.9, 0.1),legend.justification =c(1, 0),panel.background =element_rect(),legend.margin =margin(0,0,0,0, "pt"),legend.key =element_rect(colour =NA ),legend.text =element_text(hjust =0 ) )g <- g1 + g2 + g3 +plot_annotation(tag_levels ="I",title ="Using scale_fill_stepsn() & scale_fill_viridis_b() to\nachieve same results as {tmap} with {ggplot2}",theme =theme(plot.title =element_text(hjust =0.5,lineheight =0.9,size =20 ) ) ) &theme(plot.tag.location ="panel",plot.tag.position =c(0.1, 0.9),plot.tag =element_text(face ="bold",size =20 ) )ggsave(filename = here::here("book_solutions", "images", "chapter9-2-3.png"),plot = g,height =1800,width =4000,units ="px")
Figure 3
9.2.4 Scales
Scales define how values are visually represented in maps and legends, depending on the selected visual variable (e.g., fill.scale, col.scale, size.scale).
Default scale is tm_scale(), which auto-selects settings based on input data type (factor, numeric, integer).
Default values for visual variables can be checked with tmap_options().
Three main colour palette types:
Categorical: distinct colours for unordered categories (e.g., land cover classes).
Sequential: gradient from light to dark, for continuous numeric variables.
Diverging: two sequential palettes meeting at a neutral reference point (e.g., temperature anomalies).
Key considerations for colour choices:
Perceptibility: colours should match common associations (e.g., blue for water, green for vegetation).
Accessibility: use colour-blind-friendly palettes where possible.
Use of classInt::classify_intervals() for Binned Data in Maps
The classify_intervals() function from the classInt package in R is a powerful tool for visualizing continuous data in maps, such as choropleth maps. It assigns values of a continuous variable—like population density or income levels—to discrete intervals based on break points calculated by methods like Jenks or quantiles using classIntervals(). This classification enables the data to be paired with a discrete color scale, simplifying the interpretation of spatial patterns and variations across regions. For instance, after determining breaks with classIntervals(), classify_intervals() can categorize each region’s value into a bin, producing a factor suitable for plotting with libraries like ggplot2 or tmap, enhancing map readability with clear legend ranges (e.g., “10,000 - 20,000”).
Available Styles in classIntervals() and Their Uses
Below is a table summarizing the classification styles available in classIntervals() and their practical applications:
Style
Description
Use Case
fixed
Uses user-defined, fixed break points.
Custom intervals, such as policy-driven thresholds.
equal
Splits the data range into equal-width intervals.
Uniformly distributed data or when equal ranges are significant.
pretty
Rounds breaks to “nice” numbers for readability.
Visually appealing breaks for general audience maps.
quantile
Ensures each interval has roughly equal observation counts.
Skewed data distributions to show spread effectively.