Search code examples
rtmap

How to represent different borders in tmap legend


my map looks similar to this one:

# import shapefile
shape_data <- system.file("shape/nc.shp", package="sf")
shape_data <- st_read(shape_data) 
sample_data <- filter(shape_data, CNTY_ID >2100)
shape_area <- st_union(shape_data) 
#map data
tm_shape(shape_data) + tm_borders(alpha = 0.4,lwd = 0.1, col = "blue") +
tm_fill(col = "BIR79", style = "equal") +
tm_shape(sample_data)  + tm_borders(col = "red", lwd = 3, lty = 4) +
tm_shape(shape_area) + tm_borders(col = "black", lwd = 2)

the polygons in the map are distinguished by three types of boundaries, with different colours, size and, in one case, by dashes. Now, I would like to find a way to represent these 3 boundaries in a legend, either in addition to the data legend or even separate. So I would like to have the representation of the type of boundaries (red dashed, black and blue with their different size, and next to them add a text explaining what they represent, i.e. districts, boundaries of the study area and so on.

Do you have any idea how to do this with tmap? Thanks


Solution

  • Here's a solution using the viewport function from the grid package:

    library(tmap)
    library(sf)
    library(tidyverse)
    library(grid)
    
    shape_data <- system.file("shape/nc.shp", package="sf")
    shape_data <- st_read(shape_data) 
    sample_data <- filter(shape_data, CNTY_ID >2100)
    shape_area <- st_union(shape_data)
    
    tm1 <- tm_shape(shape_data) + 
      tm_fill(col = "BIR79", style = "equal") +
      tm_shape(shape_data) + tm_borders(alpha = 0.4,lwd = 1.5, col = "blue") +
      tm_shape(sample_data) + tm_borders(col = "red", lwd = 3, lty = 4) +
      tm_shape(shape_area) + tm_borders(col = "black", lwd = 2) 
    
    # add second legend
    tm_leg = tm_shape(sample_data) + tm_fill(alpha = 0) + # dummy layer
      tm_add_legend("line", 
                    col = c("blue", "red", "black"), 
                    lwd = c(1.5, 3, 2), 
                    lty = c(1, 4, 1),
                    labels = c("var1", "var2", "var3"),
                    title = "type") +
      tm_layout(legend.position = c(.15 ,-.2), 
                bg.color = NA, 
                frame = F, 
                legend.width = 10, 
                legend.height = 10)
    
    tmap_save(tm1, insets_tm = tm_leg, insets_vp = viewport(), "test_map.png")
    

    enter image description here