0

I built a terrain map of Nevada and plot the state border around it. The resulting map has a buffer-like overhang across the state border which I used to mask the raster. How can I get rid of the overhanging data? The code below makes this example easily reproducible.

    library(ggmap)
    library(raster)
    library(sf)
    library(ggplot)
    library(USAboundaries)
    state <- us_states(states = c("Nevada"))
    map3 <- get_googlemap(center = c(lon=-116.888369, lat=39.509636), zoom = 4, maptype = "terrain", color= "color",
                          style = "feature:road|visibility:off&style=feature:administrative|element:labels|visibility:off&style=feature:administrative|element:geometry|visibility:off&style=feature:landscape|visibility:on|saturation:-100|lightness:-10&style=feature:landscape|element:labels|visibility:off&style=feature:poi|visibility:off&style=feature:transit|visibility:off") 
    map.rast <- ggmap_rast(map = map3)
    map.only <- mask(map.rast, state) 
    basemap.df <- data.frame(rasterToPoints(map.only))
    
    ggplot() + 
      geom_point(data= basemap.df, aes(x=x, y=y,col=rgb(layer.1/255, layer.2/255, layer.3/255))) + 
      scale_color_identity() +
      geom_sf(data=state, color= "black", fill=NA, size=0.3, inherit.aes = F) +
      coord_sf()

enter image description here

2

The expansion is done because of the coord_sf() parameter expand = TRUE. Setting it to FALSE should remove the "buffer". Here's the corresponding part of the documentation.

ggplot() + 
      geom_point(data= basemap.df, aes(x=x, y=y,col=rgb(layer.1/255, layer.2/255, layer.3/255))) + 
      scale_color_identity() +
      geom_sf(data=state, color= "black", fill=NA, size=0.3, inherit.aes = F) +
      coord_sf(expand = F)
1
  • Thank you. This works for the some sides but not the diagonal/bottom portion. Any idea how to crop that out within the code?
    – riverotter
    Jul 7 '20 at 14:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.