Skip to content
Prev 9830 / 29559 Next

: Plot spatial data with spplot and maps

pelt wrote:

            
You?re trying to mix ?base? graphics and ?grid? graphics, which doesn?t work.
?spplot? use ?lattice? graphics (based on ?grid?), so you?ll have to modify
its ?panel? function. Here?s a very simple example.

BTW, I recommend reading the ?lattice? book to understand how to use ?panel? 
functions: http://lmdvr.r-forge.r-project.org/figures/figures.html

library(sp)
library(lattice)
library(maps)
library(maptools)
n=100

d=data.frame(x=rnorm(n,0,20),y=rnorm(n,0,20),z=1:n)
xl=range(d$x)
yl=range(d$y)
coordinates(d)=~x+y
spplot(d, panel=function(...) {
  panel.fill("lightblue3")
  wmap=map("world", fill=TRUE, plot=FALSE,
           xlim=xl, ylim=yl, resolution=0)
  wmap[c("x", "y")]=mapthin(wmap[c("x", "y")],1)
  wmap.sp=map2SpatialPolygons(wmap, wmap$names)
  sp.polygons(wmap.sp,fill="khaki", col=NA,lwd=2)
  panel.pointsplot(...)
}, xlim=xl, ylim=yl )

The reason for the slow drawing is that each polygon is plotted separately,
and the map polygon also contains areas outside ?xl? and ?yl?. (This is easy
enough to fix by merging and clipping the polygons.)