R Tmap - tm_shape 多边形下的 openstreet 层

R Tmap - openstreet layer under tm_shape polygons

我有下面的 R 代码,它使用 TMAP 在静态地图上绘制了两个图层。首先,有一个图层绘制感兴趣区域的多边形。最重要的是,绘制了一些显示销售地点的点。

我想做的是让基础层来自 openstreetmap 之类的东西,而不是从 tm_fill 中选择单一颜色。但是,我也想保留多边形结构,并让感兴趣的多边形之外的区域为白色,而不是让整个 openstreetmap 图层可见(例如,多边形之外的所有内容都是 'masked' 白色,所有内容在多边形内有 openstreetmap 图层可见)。下面是一些指导,但我无法解决,有人可以帮忙吗?

https://www.rdocumentation.org/packages/tmap/versions/3.3-2/topics/tm_basemap https://leaflet-extras.github.io/leaflet-providers/preview/

目前使用的代码:

#Plot via tm_shape
OutputMap <- tm_shape(PMSOAs) + 
  tm_fill(col = "lightgreen") +
  tm_borders(
    col = NA,
    lwd = 0.5,
    lty = "solid",
    alpha = NA,
    zindex = NA,
    group = NA
  ) +
tm_shape(SalesAddressLocations)+
  tm_dots(col = "red", size = 0.02) +
  tm_layout(title = 'Sales Locations, Date X - Date Y', title.size = 0.4, title.position = c("center", "top")) 

OutputMap

这是一个解决方案。我使用了免费提供的德国邮政编码数据,并专注于以 60(法兰克福周边地区)开头的邮政编码:

library(tidyverse)
library(sf)
library(tmap)
library(tmaptools)

# read postalcode shape file (data from https://www.suche-postleitzahl.org/downloads)
df_pc <- st_read(dsn = "data/plz-gebiete.shp/") %>%  
  as_tibble() %>% 
  filter(str_detect(plz, "^60")) %>% 
  st_as_sf

# generate 1) edge polygon unioning all postalcode geometries
# and 2) corresponding bounding box
df_pols <- st_union(df_pc) %>%  as_tibble() %>% 
 mutate(bbox = st_as_sfc(st_bbox(geometry))) %>% st_as_sf()

# compute difference between bounding box and edge polygon
diff_pol <- st_difference(df_pols$bbox, df_pols$geometry)

# read openstreetmap tile
osm <- read_osm(df_pc) 

# first plot osm content
tm_shape(osm) + 
  tm_rgb() +
# overlay difference polygon to mask content outside
tm_shape(diff_pol) +
  tm_fill(col = "white") +
# add postalcode polygons atop
tm_shape(df_pc) +
  tm_borders(lwd = 1.5, col = "darkblue") +
tm_layout(frame = F)