1

I am extremely new to working with spatial data and so most of what I'm about to say is me trying to speak a foreign language. Right now I am trying to learn how to do this all in R (I am slightly more capable with this data in QGIS but for this solution, I am looking for R only).

My research involves ecological data in Pennsylvania (PA) and so I am playing around with cropping the US NLCD dataset to PA. I have a raster layer for the NLCD and a shapefile for the boundary of Pennsylvania. I am able to successfully crop the larger US raster down to PA as follows:

library(raster)
library(rgdal)
pabound <- readOGR(dsn="...",
                   layer="PAbound")

nlcdRast <- raster(".../NLCD_2016_Land_Cover_L48_20190424.img")

pabound <- spTransform(pabound,CRS(proj4string(nlcdRast)))

PAnlcd <- raster::crop(nlcdRast,pabound)

If I run the simple plot command for both nlcdRast and PAnlcd (i.e. plot(nlcdRast) they maintain the same color scheme. But when I run it through tmap it seems to look at the cropped data differently and I am not exactly sure how to figure this out. Please see the plots below:

library(tmap)

tm_shape(nlcdRast) +
  tm_raster()

enter image description here

And then when I plot the cropped version in tmap:

tm_shape(PAnlcd) +
  tm_raster()

enter image description here

As you can see, it is not simply the color palette that is changing (I am confident I could figure that out) but the real problem is I'm losing the important information as seen in the legend. Whereas the full plot actually shows the categorical values for the raster NLCD, the cropped version now seems to show just some unknown numerical range. Even though it looks bad at the moment, I'd like to have the same legend/information as seen in the full US map.

I apologize for not having a more reproducible example but I am completely lost on what is happening here so I can't quite replicate it. I suppose right now I'm just looking for where to look to try and figure out what changed. Thank you in advance.

c.custer
  • 407
  • 5
  • 13

1 Answers1

1

Cropping is changing the way the pixels are represented. To maintain your values use the stars package (also note I'm using the sf package for the shapefile):

library(stars)
library(sf)



  # load in NLCD
    nlcdRast <- read_stars(".../NLCD_2016_Land_Cover_L48_20190424.img")
  
  # read in study area
   pabound <- st_read(dsn="...", layer="PAbound")
  
  # reproject pabound to match NLCD
   pabound <- st_transform(pabound, CRSobj = crs(nlcdRast))
  
  # now crop
   panlcd <- st_crop(nlcdRast, pabound)