Reputation: 31452
I am using rasterVis::gplot()
to plot a raster layer created by the raster
package. Plotting the raster alone works fine:
library(raster)
library(rasterVis)
r1 <- raster(nrow=10, ncol=10)
values(r1) <- runif(ncell(r1))
gplot(r1) +
geom_raster(aes(fill=value))
But when I try to add a rectangle on the plot usng geom_rect()
, I get an error
df <- data.frame(xmin=-50, xmax=50, ymin=-50, ymax=50)
gplot(r1) +
geom_raster(aes(fill=value)) +
geom_rect(data=df, aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax))
Error in eval(expr, envir, enclos) : object 'y' not found
What am I doing wrong?
Upvotes: 1
Views: 1041
Reputation: 9923
geom_rect
is expecting to have all the aesthetics declared (explicitly or implicitly) earlier, but there is no y
in df
. Use the argument inherit.aes = FALSE
to turn this behaviour off.
gplot(r1) +
geom_raster(aes(fill=value)) +
geom_rect(data=df, aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax),
inherit.aes = FALSE)
Alternatively, use annotate
to add the rectangle.
gplot(r1) +
geom_raster(aes(fill=value)) +
with(df, annotate(geom = "rect", xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax))
Upvotes: 1