2

I'm attempting to create a map in R using library(tmap) with a full-color RGB, masked Landsat image. The NAs however appear as black. Here's what I did.

Using library(sf) I calculated the centroids of 5 polygons and buffered them by 5000m. Following this I used library(raster) to mask a Landsat image by the buffered centroids. The code looks like this and works perfectly.

# Read in the data
polys <- st_read("nybb.shp")
rast <- brick("LC08_L1TP_013032_20171027_20171027_01_RT.tif")

# Transform polys, crop raster, calculate centroids
polys <- st_transform(polys, crs = crs(rast, asText = TRUE))
rast <- crop(rast, as(polys, "Spatial"))
cent <- st_centroid(polys) %>% st_buffer(., 5000) %>% as(., "Spatial")

# Mask the raster using buffered centroids
r <- mask(rast, cent)

I can accomplish what I want using base R and library(raster) -- BUT I would prefer to do this using tmap.

# Code that works
plot(polys$geometry, col = "grey", border = "white")
plotRGB(r, bgalpha = 0, add = TRUE) 


# Code that does not work
# The NAs in the masked raster appear as black
# even when using the colorNA argument
tm_shape(polys) + tm_polygons() + 
  tm_shape(r, bbox = polys) + 
  tm_rgb(colorNA = "red")

Any idea how to show the masked raster using tmap's tm_rgb() function without showing the NAs as black?

kit444
  • 21
  • 3

1 Answers1

0

To create a basemap with tmap, you can use the read_osm function, from the tmaptools package as follows. Note that you must first transform the data into a geographical CRS: epsg=4326

library(tmaptools)
library(OpenStreetMap)

rast <-projectRaster(rast,crs="+init=epsg:4326",method = "ngb") #(you can use method=method="bilinear") 

polys <- spTransform(polys, CRS("+init=epsg:4326"))

background <- read_osm(bbox(rast))

tm_shape(background) + tm_raster() +
tm_shape(polys) + tm_polygons() + 
tm_shape(r, bbox = polys) + 
tm_rgb(colorNA = "red")
francisco corvalan
  • 300
  • 1
  • 4
  • 10