Search code examples
rrasterr-sfggmap

Removing the grey shading outside of masked raster in ggmaps


I have some code here for plotting a map with masked raster datapoints.

Here I define a random dataframe:

set.seed(20)
lon = seq(from = 3.4, to = 6.3, by = 0.1)
lat = seq(from = 13.3, to = 10.1, by = -0.1)

lati <- c()
long <- c()
for (i in 1:length(lat)) {
  for (j in 1:length(lon)) {
    lati <- c(lati,lat[i])
    long <- c(long,lon[j])
  }
}

vals = rnorm(length(lati))

df <- data.frame(
  longitude=long,
  latitude=lati,
  value=vals)

Here I make the boundaries for a map:

library(raster)
library(sf)
library(ggplot2)
nga <- getData('GADM', country='NGA', level=1)
keb <- subset(nga,NAME_1 %in% "Kebbi")
keb2 <- st_as_sf(keb)

This is the masking process of the dataframe:

spg <- df
coordinates(spg) <- ~ longitude + latitude
gridded(spg) <- TRUE
rasterDF <- raster(spg)
rasterDF_crop <- crop(rasterDF, extent(keb2))
rasterDF_masked <- mask(rasterDF_crop, keb2)
df_masked <- raster::as.data.frame(rasterDF_masked,xy=TRUE)
colnames(df_masked) <- colnames(df)

I then make a map with "ggmap":

library(ggmap)
slat <- min(df_masked$latitude)-0.3
slon <- min(df_masked$longitude)-0.3
llat <- max(df_masked$latitude)+0.3
llon <- max(df_masked$longitude)+0.3
kebbox <- c(left=slon,bottom=slat,right=llon,top=llat)
kebMap <- get_stamenmap(bbox=kebbox,zoom=8,maptype="toner")
keb_map <- ggmap(kebMap,extent="panel")

Then I make the new map with masked raster:

tilekeb <- keb_map + geom_tile(data=df_masked,aes(x=longitude,y=latitude,fill=value),alpha=1/2,color="black",size=0) +
  geom_sf(data = keb2, inherit.aes = FALSE, fill = NA)

tilekeb

The map looks like this:

enter image description here

I want to remove the grey shading outside of the masked raster:

enter image description here

Thanks!


Solution

  • You need to set the color for the NA values used in geom_tile. To do that, add a line scale_fill_continuous(na.value = NA).

    See https://stackoverflow.com/a/35069695/12400385

    tilekeb <- keb_map + 
      geom_tile(data=df_masked,
                aes(x=longitude,y=latitude,fill=value),
                alpha=1/2,
                #color="black",
                size=0) +
      scale_fill_continuous(na.value = NA) +
      geom_sf(data = keb2, inherit.aes = FALSE, fill = NA)
    
    tilekeb
    

    enter image description here