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)

What are 'components' in tmap?

Components are non-spatial parts of the plots:

Title and credits

tm_title() and tm_credits() add text to the map in the form a title and a credits/attribution text respectively. The underlying function and all the options are the same, but the default value differ: titles are by default larger and placed above the map (outside the frame), while credits are place inside the frame at the bottom right.

tm_shape(NLD_muni) +
  tm_polygons(
    fill = "edu_appl_sci") +
tm_title("Population share with (applied) university degree in 2022") +
tm_credits("Statistics Netherlands (CBS)")

Scale bar and compass

tm_shape(NLD_muni) +
  tm_polygons() +
    tm_compass(type = "8star") +
    tm_scalebar()

Positioning of components (basics)

The position of a map component can be specified with the general argument position.

It takes a vector of two, the first is the horizontal position ("left", "center", "right"), the second one the vertical position ("top", "center", "bottom")

tm_shape(NLD_muni) +
  tm_polygons(
    fill = "edu_appl_sci",
    fill.legend = tm_legend(position = c("left", "top"))) +
tm_credits("Statistics Netherlands (CBS)", position = c("left", "bottom")) +
tm_compass(type = "8star", position = c("right", "bottom")) +
tm_scalebar(position = c("right", "bottom"))

If the components should be placed tighter to the frame, use capital case instead; e.g. c("LEFT", "BOTTOM") in stead ofc("left", "bottom")`.

There are much more options to position map componets via tm_pos(), see the vignette about positions



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