简体   繁体   English

如何在 tmap 图例中表示不同的边框

[英]How to represent different borders in tmap legend

my map looks similar to this one:我的 map 看起来与这个类似:

# 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. map 中的多边形通过三种类型的边界来区分,具有不同的颜色、大小,并且在一种情况下,通过破折号。 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.现在,我想找到一种在图例中表示这 3 个边界的方法,除了数据图例之外,甚至分开。 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, ie districts, boundaries of the study area and so on.所以我想要边界类型的表示(红色虚线、黑色和蓝色,它们的大小不同,然后在它们旁边添加一个文本来解释它们所代表的内容,即地区、研究区域的边界等。

Do you have any idea how to do this with tmap?你知道如何用 tmap 做到这一点吗? Thanks谢谢

Here's a solution using the viewport function from the grid package:这是使用grid package 中的viewport function 的解决方案:

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")

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM