Search code examples
rraster

Adding text labels to a raster plot


The script:

library(raster)
places = data.frame(x=c(0.2, 0.7), y=c(0.2, 0.7), name=c('A','B'), stringsAsFactors=F)
plot(raster(volcano))
points(places$x, places$y, pch=16)
text(places$name, places$x, places$y-0.1)

fails on the last line with the message: In xy.coords(x, y, recycle = TRUE) : NAs introduced by coercion. I think this is due to mixing graphics libraries, but the text function in raster only seems to apply to raster-formatted text objects. Grateful for advice on how to add discrete points on a raster plot.


Solution

  • You can use graphics::text as normal, but it expects x, y as the first arguments, just like points and many other xy.coords functions:

    text(x = places$x, y = places$y-0.1, labels = places$name)