R package for thematic maps
knitr::opts_chunk$set(
collapse = TRUE,
out.width = "100%",
dpi = 300,
fig.width = 7.2916667,
comment = "#>",
fig.path = "man/figures/README-"
)
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)
})
tmap is an R package for drawing thematic maps. The API is based on A Layered Grammar of Graphics and resembles the syntax of ggplot2, a popular R-library for drawing charts.
Installation of tmap is straightforward:
install.packages("tmap")
For Linux and macOS users who are new to working with spatial data in R, this may fail since additional (non-R) libraries are required (which are automatically installed for Windows users).
The development version can be installed from the GitHub repository using
remotes
or pak
packages or from the R-universe repository.
# install.packages("remotes")
remotes::install_github("r-tmap/tmap")
# install.packages("pak")
pak::pak("r-tmap/tmap")
# Or from R-universe
install.packages("tmap", repos = c("https://r-tmap.r-universe.dev", "https://cloud.r-project.org"))
Windows
No additional installation required.
Linux (Ubuntu)
See https://geocompx.org/post/2020/installing-r-spatial-packages-linux/. Please address installation issues in this issue.
macOS
See https://www.kyngchaos.com/. Please address installation issues in this issue.
library(tmap)
Plot a World map of the happy planet index (HPI) per country.
The object World
is an example spatial data frame (sf
) object that is contained in tmap:
tm_shape(World) +
tm_polygons(fill = "HPI")
This map can be enhanced in several ways.
For instance:
tm_shape(World, crs = "+proj=robin") +
tm_polygons(fill = "HPI",
fill.scale = tm_scale_continuous(values = "matplotlib.rd_yl_bu"),
fill.legend = tm_legend(title = "Happy Planet Index",
orientation = "landscape",
frame = FALSE)
)
The book Geocomputation with R provides a chapter on Making maps with R, including a section on tmap.