knitr::opts_chunk$set(
  collapse = TRUE,
  out.width = "100%",
  dpi = 300,
  fig.width = 7.2916667,
  comment = "#>"
)
hook_output <- knitr::knit_hooks$get("output")
knitr::knit_hooks$set(output = function(x, options) {
   lines <- options$output.lines
   if (is.null(lines)) {
     return(hook_output(x, options))  # pass to default hook
   }
   x <- unlist(strsplit(x, "\n"))
   more <- "..."
   if (length(lines)==1) {        # first n lines
     if (length(x) > lines) {
       # truncate the output, but add ....
       x <- c(head(x, lines), more)
     }
   } else {
     x <- c(more, x[lines], more)
   }
   # paste these lines together
   x <- paste(c(x, ""), collapse = "\n")
   hook_output(x, options)
 })
library(tmap)
tmap_options(scale = 0.75)

About the data

In tmap, there are two example data sets of the Netherlands:

The first two datasets contain demographic data of the Netherlands as of 2022. The third dataset only contains metadata (names and codes) and will only be used to plot province borders.

tmap_arrange(
    qtm(NLD_dist, title = "NLD_dist: 3340 districts"),
    qtm(NLD_muni, title = "NLD_mini: 345 municipalities"),
    qtm(NLD_prov, title = "NLD_prov: 12 provinces"),
    ncol = 3
)

The variables in the NLD_dist and NLD_muni are the same:

names(NLD_dist)

We will create a choropleth about the variable "edu_appl_sci", which contains the percentage of 15-75 year old people who have a university degree (Dutch: WO) or applied sciences degree (Dutch: HBO), per district as of 1st October 2022.

Choropleth: step 1

tm_shape(NLD_dist) +
    tm_polygons(fill = "edu_appl_sci") # data variable -> fill color

Choropleth: step 2

We remove the district borders, because they are too dense in urban areas. Instead, we add borders of municipalities and provinces op top:

tm_shape(NLD_dist) +
    tm_polygons(
        fill = "edu_appl_sci",
        col = NULL) +           # disable border lines
tm_shape(NLD_muni) +
    tm_borders(lwd = 1) +       # municipality border line width 1
tm_shape(NLD_prov) +
    tm_borders(lwd = 3)         # province border line width 3

Choropleth: step 3

A few improvements and embellishments:

tm_shape(NLD_dist) +
    tm_polygons(
        fill = "edu_appl_sci",
        fill.scale = tm_scale_continuous(values = "-orange_blue_diverging"),
        fill.legend = tm_legend("", position = tm_pos_in("left", "top")),
        col = NULL
    ) + 
tm_shape(NLD_muni) +
    tm_borders(lwd = 1) +
tm_shape(NLD_prov) +
    tm_borders(lwd = 3) + 
tm_title("Proportion of Population Aged 15–75 with a University or Applied Sciences Degree by District (as of October 1, 2022)", 
    width = 15, 
    position = tm_pos_in("left", "top"), 
    z = 0) +
tm_compass(position = tm_pos_in("left", "bottom")) +
tm_scalebar(position = tm_pos_in("left", "bottom")) +
tm_credits("© Data: Statistics Netherlands, Software: R-tmap",
    position = tm_pos_in("left", "bottom"))


r-tmap/tmap documentation built on Feb. 28, 2025, 7:54 a.m.