With the tmap package, thematic maps can be generated with great flexibility. The syntax for creating plots is similar to that of ggplot2
, but tailored to maps. This vignette is for those who want to get started with tmap within a couple of minutes. A more detailed description of tmap can be found in an article published in the Journal of Statistical Software (JSS), which describes tmap version 1.11-2. The changes in version 2.0 are described in vignette("tmap-changes-v2")
.
For more context on R’s geographic capabilities there are a number of online resources including the vignettes of the sf
package, the website rspatial.org and the online version of the book Geocomputation with R. The Making maps with R chapter of the book provides many more context and abundant code examples of map making with tmap
and other packages.
A good place to start is to create a map of the world. After installing tmap, the following lines of code should create the map shown below:
library(tmap)
data("World")
tm_shape(World) +
tm_polygons("HPI")
The object World
is a spatial object of class sf
from the sf package; it is a data.frame
with a special column that contains a geometry for each row, in this case polygons. In order to plot it in tmap, you first need to specify it with tm_shape
. Plotting layers can be added with the +
operator, in this case tm_polygons
. There are many layer functions in tmap, which can easily be found in the documentation by their tm_
prefix. See also ?'tmap-element'
.
Each map can be plotted as a static image or viewed interactively using "plot"
and "view"
modes, respectively. The mode can be set with the function tmap_mode
, and toggling between the modes can be done with the ‘switch’ ttm()
.
tmap_mode("view")
tm_shape(World) +
tm_polygons("HPI")
A shape is a spatial object (with a class from sf
, sp
or raster
). Multiple shapes and also multiple layers per shape can be plotted:
data(World, metro, rivers, land)
tmap_mode("plot")
## tmap mode set to plotting
tm_shape(land) +
tm_raster("elevation", palette = terrain.colors(10)) +
tm_shape(World) +
tm_borders("white", lwd = .5) +
tm_text("iso_a3", size = "AREA") +
tm_shape(metro) +
tm_symbols(col = "red", size = "pop2020", scale = .5) +
tm_legend(show = FALSE)
Facets can be created in three ways:
tmap_mode("view")
tm_shape(World) +
tm_polygons(c("HPI", "economy")) +
tm_facets(sync = TRUE, ncol = 2)
by
argument of tm_facets
:tmap_mode("plot")
## tmap mode set to plotting
data(NLD_muni)
NLD_muni$perc_men <- NLD_muni$pop_men / NLD_muni$population * 100
tm_shape(NLD_muni) +
tm_polygons("perc_men", palette = "RdYlBu") +
tm_facets(by = "province")