[R-sig-Geo] Plotting polygons on top of a levelplot

Ryan Anderson ryan.anderson at ntsg.umt.edu
Mon Aug 11 21:40:28 CEST 2008


I have some gridded spatial data that I want to plot with a vector overlay
on top.  The following reproducible code makes a figure similar to the one
I am ultimately trying to produce:

library(sp)
library(fields)
data(meuse.grid)
data(meuse.riv)
coords <- SpatialPixels(SpatialPoints(meuse.grid[, c("x","y")]))
spdf <- SpatialPixelsDataFrame(coords, meuse.grid)
fullgrid(spdf)<-TRUE
river<-SpatialPolygons(list(Polygons(list(Polygon(meuse.riv)),"meuse.riv")))
par(mar = c(5,5,5,8), col.axis = 1)
ramp = heat.colors(400)
image(spdf, "dist", axes = TRUE, col = ramp)
plot(river, add = TRUE)
zvals<-spdf$dist
zvals<-zvals[!is.na(zvals)]
image.plot(zlim = c(min(zvals), max(zvals)), nlevel = 256, legend.only =
TRUE, col = ramp)

I need more control over the legend and the color ramp than I know how to
achieve with this code.  I can create the plot I want with levelplot by
setting the 'at' component 'colorkey', but when I try to overlay the
vector file I get an error.  Here is a simplified version of the code I
tried:

#try a levelplot
library(lattice)
x11()
par(mar = c(5,5,5,8))
x<-spdf$x
y<-spdf$y
z<-spdf$dist
levelplot(z~x+y)
plot(river, add = TRUE)
#Gives Error in polygon(x = x, y = y, border = border, col = col, lty =
#lty,  :
#  plot.new has not been called yet

I need to either find a way to control the mapping of data values to the
color ramp more precisely in my call to image or image.plot or to find a
way to plot a ploygon over the top of a levelplot.

My color ramp goals more specifically: my grid contains both positive and
negative values, and they are not necessarily symmetrically distributed
around zero.  I want to plot them so that zero is white, negative values
are symbolized with a ramp from white to blue (with darker shades for
lower values) and positive values are symbolized with a ramp from white to
red (with darker shades for higher values).

Thanks for your help!




More information about the R-sig-Geo mailing list