knitr::opts_chunk$set(
  collapse = TRUE,
  fig.width = 8,
  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)

Modes

tmap facilitates two output modes: "plot", which produces static maps, and "view" which produces (using the same tmap code) interactive maps (using the JavaScript library Leaflet as backend).

Via the extension package, tmap.mapgl, two new modes are available: "mapbox" and "maplibre", as demonstrated below.

Switching between modes

## current mode
tmap_mode()

## to view mode
tmap_mode("view")

## back to plot mode
tmap_mode("plot")

The handy function ttm() is used to toggle between the modes. When more than two modes are loaded, rtm() can be used to rotate between modes.

Mode "plot"

We start with creating the plot and assign it to a variable called tm.

tm = tm_shape(World, crs = 8857) +
  tm_polygons(
    fill = "press",
    fill.scale = tm_scale_intervals(values = "pu_gn")) +
tm_shape(metro) +
  tm_bubbles(
    size = "pop2020",
    fill = "gold",
    size.scale = tm_scale_continuous(values.scale = 0.8, n = 8))

We are in "plot" mode. Now we can plot the map by printing the tm object:

tm

Mode "view"

The same map in view mode:

ttm()
tm

Note that there is a big difference: in "view" mode there are basemaps, and in "plot" mode none. This is caused by different default options.

Basemaps can be enabled or disabled via tm_basemap():

tm + tm_basemap(NULL)

See vignette about basemaps.

Mode specific options

Mode specific layout options can be set via tm_plot() and tm_view(). The number of options in tm_plot() is limited to just two, because it uses all general purpose options. In contrast, tm_view() contains more options, e.g. the position of the control box and the default zoom level:

tm +
    tm_view(control.position = c("left", "bottom"),
            set_view = 2)

For a more detailed description of the available options, see the vignette about options.

mapgl modes: "mapbox" and"maplibre"`.

The new package mapgl offers two new modes. The first is "mapbox" for which an API key is required, which is free for personal use. The second is maplibre for which no API key is required.

library(tmap.mapgl)
tmap_mode("maplibre")

tm


r-tmap/tmap documentation built on June 1, 2025, 1:56 p.m.