自定义tm_compass()背景

时间:2018-02-02 14:48:04

标签: r maps tmap dismo

在下面的代码中,我如何为地图标题设置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))

enter image description here 感谢

2 个答案:

答案 0 :(得分:1)

看到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)

enter image description here

答案 1 :(得分:0)

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)