删除ggmaps中蒙版栅格外部的灰色阴影

Removing the grey shading outside of masked raster in ggmaps

我这里有一些代码用于绘制带有屏蔽栅格数据点的地图。

这里我定义了一个随机数据帧:

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)

这里我画了一张地图的边界:

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)

这是数据帧的屏蔽过程:

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)

然后我用“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")

然后我用蒙版栅格制作新地图:

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

地图看起来像这样:

我想移除蒙版栅格外的灰色阴影:

谢谢!

您需要为 geom_tile 中使用的 NA 值设置颜色。为此,添加一行 scale_fill_continuous(na.value = NA).

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