1

I'm trying something very trivial - cropping a large raster to a smaller extent using a sf object. The raster is cropped with no errors but when I try and plot the cropped raster I get the following error:

Error in .plotraster2(x, col = col, maxpixels = maxpixels, add = add,  : 

no values associated with this RasterLayer

Both the raster and sf object are in the same crs/projection.

I wonder if it has anything to do with the versions of raster/rgdal and the GDAL/PROJ libraries that these packages are compiled against?

I'm using Ubuntu 20.04, R version 3.6.3.

Here's my simple script:

library(sf)
library(raster)

sourceFile <- file.path('cigGhana_25.geojson')
gridGhana <- raster('gha_px_area_100m.tif')


# subset
shp <- st_read(sourceFile)
shp = shp[1,] # select on feature from the sf collection
grd <- raster(gridGhana)
grd <- crop(grd, extent(shp)) # crop grid to extent of the shp


plot(grd)
#Error in .plotraster2(x, col = col, maxpixels = maxpixels, add = add,  : 
#                        no values associated with this RasterLayer

And my source raster and vector files are here:

https://drive.google.com/file/d/1stmPsEOMek-1J5vJBPRcGyVLAIh1jgx9/view?usp=drivesdk

https://drive.google.com/file/d/11-VKlOksQKdy_mafFg9UpoR2HIo47lqo/view?usp=drivesdk

1 Answer 1

1

You loaded gridGhana with

gridGhana <- raster('gha_px_area_100m.tif')

But when doing

grd <- raster(gridGhana)

You actually created an empty raster using gridGhana as template. So grd is just empty, this is why it does not plot.

library(sf)
library(raster)

shp <- st_read('cigGhana_25.geojson')
gridGhana <- raster('gha_px_area_100m.tif')

shp = shp[1,] # select on feature from the sf collection
grd <- crop(gridGhana, extent(shp)) # crop grid to extent of the shp

plot(grd)
1
  • thanks, silly me. Thanks that's just the ticket!
    – marty_c
    Nov 22, 2021 at 10:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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