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)

Basemaps

By default, basemaps are only shown in "view" mode, so not in "plot" mode. Basemaps can be enabled or disabled via tm_basemap().

Plot mode

To enable a basemap in plot mode, the package maptiles is required. When specified without arguments, the default basemap server is "Esri.WorldGrayCanvas" (run tmap_options("basemap.server") to see this option). This can be changed, e.g. "OpenTopoMap".

tm_shape(metro) +
    tm_bubbles(size = "pop2020") +
    tm_basemap("OpenTopoMap")

The options are:

names(maptiles::get_providers())

See previews

tm_shape(metro) +
    tm_bubbles(size = "pop2020") +
    tm_basemap("CartoDB.PositronNoLabels")

Note: the Esri basemaps (also the default) do not render well issue

View mode

In view mode, there are even more options. There can be obtained via names(leaflet::providers).

tmap_mode("view")
tm_shape(metro) +
    tm_bubbles(size = "pop2020") +
    tm_basemap("Esri.OceanBasemap")

Disabling basemaps:

tmap_mode("view")
tm_shape(World) +
  tm_polygons(
    fill = "grey80", 
    col = "grey60") +
tm_shape(metro) +
    tm_bubbles(size = "pop2020") +
    tm_basemap(NULL)

Now it is also possible to use different map projections (see vignette):

tmap_mode("view")
tm_shape(World, crs = "+proj=robin") +
  tm_polygons(
    fill = "grey80", 
    col = "grey60") +
tm_shape(metro) +
    tm_bubbles(size = "pop2020") +
    tm_basemap(NULL)


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