rmapstmapdismo

Customize tm_compass() background


In the code below, how do I set background color and transparency fortm_compass()as I can do for map title?

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 Thanks


Solution

  • Seeing the CRAN manual, I thought it would not be possible to do the job. My workaround was to manually create a polygon that covers the compass. This is a tedious work, but this is perhaps the way to go right now. The first step is to create a polygon. extent() gives you min and max for longitude and latitude. I used xmax and ymax to specify five points for a polygon. (I played with values and found the optimal values.) We need to assign a right projection to the polygon. If you type ny.map in your R Console, you will see coord. ref.. This is the projection you need. Then, I added the polygon to the map using tm_shape() and 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