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)
library(dplyr)
library(sf)
tmap_options(scale = 0.75)

About the data

A spatial data object contained in tmap is called World. It is a data frame with a row for each country. The columns are the following data variables plus an additional geometry column which contains the geometries (see sf package):

names(World)

We will create a choropleth of the Gender Inequality Index (GII) per country.

The choropleth: step 1

tm_shape(World) +
    tm_polygons(fill = "gender")

The choropleth: step 2

A few improvements:

tm_shape(World, crs = "+proj=eqearth") +
  tm_polygons(
    fill = "gender",
    fill.scale = tm_scale_intervals(values = "-tableau.classic_orange_blue"),
    fill.legend = tm_legend(
     "Gender Inequality Index (GII)", 
    position = tm_pos_on_top(pos.h = "left", pos.v = "bottom"), 
    bg.color = "white")) +
tm_options(earth_boundary = TRUE, frame = FALSE)


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