I am trying to help a friend with a plot, but end up getting stuck.
He wants to plot sample locations on a levelplot. The raster is from the package unmarked
. (data(Switzerland)
). I have tried it with a dummy dataframe, where I randomly chose some locations.
I have found the following question Add XY points to raster map generated by levelplot which is more or less what I would like to do.
So I have tried the following code:
x <- c("980000", "1100000", "1200000")
y <- c("120000", "170000", "100000")
name <- c("a", "b", "c")
dummy <- as.data.frame(cbind(x, y, name))
levelplot(elevation ~ x + y, Switzerland, aspect="iso",col.regions=terrain.colors(100)) +
layer(sp.points(dummy, cex=2, col=1))
But I end up with an error message
Error in .local(obj, ...) : any(sp) is not TRUE
I tried to understand what sort of input sp.points()
needs and what I'm doing wrong, but failed.
Convert dummy
to an sp
-object, i.e., a SpatialPointsDataFrame
in your case:
R> library("sp")
R> dummy <- data.frame(x = as.numeric(x), y = as.numeric(y), name = name)
R> coordinates(dummy) <- ~ x + y
R> class(dummy)
[1] "SpatialPointsDataFrame"
attr(,"package")
[1] "sp"
Reproducible example:
library("sp")
library("lattice")
library("latticeExtra")
library("unmarked")
data(Switzerland)
x <- c(980000, 1100000, 1200000)
y <- c(120000, 170000, 100000)
name <- c("a", "b", "c")
dummy <- data.frame(x, y, name)
coordinates(dummy) <- ~ x + y
p <- levelplot(elevation ~ x + y, Switzerland,
aspect = "iso", col.regions = terrain.colors(100)) +
layer(sp.points(dummy, cex = 2, col = 1))
print(p)