自定义 tm_compass() 背景

Customize tm_compass() background

在下面的代码中,如何像设置地图标题一样设置tm_compass()的背景颜色和透明度?

library(tmap)
library(dismo)

ny.map <- gmap(x = "New York", zoom = 13, type = "satellite")

print(tm_shape(shp = ny.map) +
      tm_raster() +
      tm_compass(position = c("right", "top"),
                 type = "4star",
                 show.labels = 2) +
      tm_layout(title = "New York",
                title.bg.color = "white",
                title.bg.alpha = 0.5))

谢谢

看了CRAN手册,还以为做不了呢。我的解决方法是手动创建一个覆盖罗盘的多边形。这是一项乏味的工作,但这也许是现在要走的路。第一步是创建多边形。 extent() 为您提供经度和纬度的最小值和最大值。我使用 xmax 和 ymax 为多边形指定五个点。 (我试过值并找到了最佳值。)我们需要为多边形分配一个正确的投影。如果您在 R 控制台中键入 ny.map,您将看到 coord. ref.。这是您需要的投影。然后,我使用 tm_shape()tm_fill().

将多边形添加到地图中
lon <- c(extent(ny.map)[2]-2100, extent(ny.map)[2]-250, extent(ny.map)[2]-250, extent(ny.map)[2]-2100, extent(ny.map)[2]-2100)
lat <- c(extent(ny.map)[4]-250, extent(ny.map)[4]-250, extent(ny.map)[4]-2100, extent(ny.map)[4]-2100,extent(ny.map)[4]-250)

foo <- SpatialPolygons(list(Polygons(list(Polygon(cbind(lon, lat))), ID = 1)),
                   proj4string = CRS("+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs"))

tm_shape(shp = ny.map) +
tm_raster() +
tm_shape(shp = foo) +
tm_fill("red", alpha = 0.4) +
tm_compass(position = c("right", "top"),
           type = "4star",
           show.labels = 2) +
tm_layout(title = "New York",
          title.bg.color = "white",
          title.bg.alpha = 0.5)

tmap 3.1 版开始支持自定义 tm_compass()(和 tm_scale_bar())背景:

library(spData)
library(tmap)

tm_shape(elev) +
  tm_raster() + 
  tm_compass(bg.color = "white", 
             bg.alpha = 0.7,
             type = "8star",
             position = c("left", "bottom"),
             size = 3) +
  tm_layout(legend.show = FALSE)