dww
dww

Reputation: 31452

Draw rectangle on gplot of raster map

I am using rasterVis::gplot() to plot a raster layer created by the rasterpackage. 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))

enter image description here

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

Answers (1)

Richard Telford
Richard Telford

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

Related Questions