Skip to content
Prev 7210 / 29559 Next

plot shape file using lattice xyplot

On Wed, 16 Dec 2009, Zia Ahmed wrote:

            
This look like a two-step question, assuming that you need a line 
representation of possible polygon boundaries from the shapefile. If it is 
a SpatialLines object, omit the first step (it will work on 
SpatialPolygons* objects with appropriate slot names, but the intention 
is to use lines, so make sure that they are):

library(sp)
library(maptools)
xx <- readShapeSpatial(system.file("shapes/sids.shp",
   package="maptools")[1])
proj4string(xx) <- CRS("+proj=longlat +ellps=clrk66")
# assigning geographical coordinates for this data set
class(xx)

lxx <- as(xx, "SpatialLines")
class(lxx)

lns <- slot(lxx, "lines")
olns <- lapply(lns, slot, "Lines")
ocrds <- matrix(nrow=0, ncol=2)
for (i in seq(along=olns)) {
   for (j in seq(along=olns[[i]])) {
     crds <- rbind(slot(olns[[i]][[j]], "coords"), c(NA, NA))
     ocrds <- rbind(ocrds, crds)
   }
}

plot(ocrds, type="l")
# sanity check

pts <- coordinates(spsample(xx, n=400, type="random"))

library(lattice)
xyplot(y~x, as.data.frame(pts), pch=1, cex=.8, col="black",
   xlab=list("Easting (m)",cex=.9), ylab=list("Northing (m)",cex=.9),
   aspect = mapasp(xx), # setting aspect for geographical coordinates
   panel = function(...) {
     panel.xyplot(...)
     panel.lines(ocrds)
   }
)

In summary: make an S-style coordinates matrix (lines separated by NA 
rows), then pass through panel.lines().

Hope this helps,

Roger