I followed this answer to create raster files for each attribute in a shapefile and got a RasterBrick at the end. But when I try to plot it using gplot
or ggplot2
, it throws an error. I tried reading the file again and then stacking it, but the error is the same.
Link for creating the raster: https://stackoverflow.com/a/47664716/11696009
Error while using gplot
:
> gplot(data = x) + geom_tile(aes(fill = value)) + facet_wrap(~ variable)
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘gplot’ for signature ‘"missing"’
With ggplot2
it throws the following error:
> ggplot(data = x) + geom_tile(aes(fill = value)) + facet_wrap(~ variable) + theme_bw()
Error in `fortify()`:
! `data` must be a <data.frame>, or an object coercible by `fortify()`, not an S4 object with class <RasterBrick>.
Run `rlang::last_error()` to see where the error occurred.
Please help me how to resolve this or at least what the reason for this error is.
Reproducible example:
library(raster)
library(rasterVis)
library(ggplot2)
r <- raster(ncols=36, nrows=18)
p1 <- rbind(c(-180,-20), c(-140,55), c(10, 0), c(-140,-60), c(-180,-20))
hole <- rbind(c(-150,-20), c(-100,-10), c(-110,20), c(-150,-20))
p1 <- list(p1, hole)
p2 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55), c(-10,0))
p3 <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45), c(-125,0))
att <- data.frame(id=1:3, var1=10:12, var2=c(6,9,6))
pols <- spPolygons(p1, p2, p3, attr=att)
pols$id <- 1:nrow(pols)
r <- rasterize(pols, r, field='id')
x <- subs(r, data.frame(pols), by='id', which=2:ncol(pols), filename="rstr.grd")