0

I've just started with mapping in R and I've managed to convert a lat, lon dataframe to a raster file and then plot state borders on top of that.

enter image description here

Now I need to get it ready to publish and would like to include only the shape of my 13-state region (and no great lakes).

library(tmap)    

usa <- st_as_sf(maps::map("state", fill=TRUE, plot =FALSE))

map_us<- tm_shape(usa)+
    tm_borders()  

tm_shape(raster_file) + 
  tm_raster(style = "cont", palette = "viridis", midpoint = 0)+
  map_us  

I'm having a hard time finding something out there that would provide a polygon for multiple states and I have been through a lot of mapping packages. Sorry I can't include my raster data here.

Nazer
  • 3,654
  • 8
  • 33
  • 47
  • Just to be clear, you want great lakes to be excluded from `map_us`, right? – M-- Oct 07 '19 at 19:51
  • Yes! Just North Dakota, South Dakota, Nebraska, Kansas, Missouri, Iowa, Minnesota, Wisconsin, Illinois, Indiana, Ohio, Wisconsin, and Michigan. No lakes. – Nazer Oct 07 '19 at 19:53
  • Well it's not that easy. I don't think there's a raster out there with waterbodies excluded from the map. you need to exclude them manually. That's what I think tho, maybe someone has a better idea. – M-- Oct 07 '19 at 20:11

1 Answers1

1

To crop a raster file to {sf} vector shape you have in principle two options:

  • crop at data level; this involves raster::mask() with possibly raster::crop() later to reduce the extent of the raster (masked raster retains the original size)
  • retain the data, and overlay a white polygon with a hole over your plot

Cropping on data level is more "pure", but will leave you with ragged edges (a raster cell has to be square).

Overlaying a white polygon is not so pure, but might be preferable if your key aim is a slick presentation (and purity of essence be damned...)

You will find both of them discussed, together with examples and sample code, in this post on the RStudio community site.

Jindra Lacko
  • 7,814
  • 3
  • 22
  • 44