Skip to content
Prev 25036 / 29559 Next

Add layers to a lattice plot via a for loop

Oops, I didn't run the example in a clean, new session. Here is that an update that should work:


library(maps)
library(maptools)
library(sp)
library(latticeExtra)

coast <- map(fill = TRUE, plot = FALSE)
coast <- map2SpatialLines(coast)
coast <- SpatialLinesDataFrame(coast, data.frame(z = seq_len(length(coast))))
tracks <- list(SpatialPoints(cbind(c(90, 90), c(-20, 20))),
               SpatialPoints(cbind(c(-90, -90), c(-20, 20))))

p <- spplot(coast, col.regions = "darkgray", colorkey = FALSE)
p <- p + layer(sp.points(tracks[[1]], pch = 19, col = 1))
p <- p + layer(sp.points(tracks[[2]], pch = 19, col = 2))
print(p) # shows both tracks

p <- spplot(coast, col.regions = "darkgray", colorkey = FALSE)
for (k in seq_along(tracks))
  p <- p + layer(sp.points(tracks[[k]], pch = 19, col = k))
print(p) # shows the second (red) track only

The R environment is:
R version 3.3.1 (2016-06-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Thanks,

D