Skip to content

Clip a contour with shapefile while using contourplot

1 message · Paul Murrell

#
Hi

Below is some code that does what I think you want by drawing a path 
based on the map data.  This does some grubby low-level work with the 
'sp' objects that someone else may be able to tidy up


# The 21st polygon in 'hello' is the big outer boundary
# PLUS the 20 other inner holes
map <- as(hello, "SpatialPolygons")[21]
# Convert map outline to path information
polygonsToPath <- function(ps) {
	# Turn the list of polygons into a single set of x/y
	x <- do.call("c",
	             sapply(ps,
	                    function(p) { p at coords[,1] }))
	y <- do.call("c",
	             sapply(ps,
	                    function(p) { p at coords[,2] }))
	id.lengths <- sapply(ps, function(p) { nrow(p at coords) })
	# Generate vertex set lengths
	list(x=x, y=y, id.lengths=id.lengths)
}
path <- polygonsToPath(map at polygons[[1]]@Polygons)
# Generate rect surrounding the path
xrange <- range(path$x)
yrange <- range(path$y)
xbox <- xrange + c(-50000, 50000)
ybox <- yrange + c(-50000, 50000)
# Invert the path
invertpath <- list(x=c(xbox, rev(xbox), path$x),
                    y=c(rep(ybox, each=2), path$y),
                    id.lengths=c(4, path$id.lengths))
# Draw inverted map over contourplot
contourplot(Salinity ~ Eastings+Northings | Time, mydata,
             cuts=30, pretty=TRUE,
             panel=function(...) {
                 panel.contourplot(...)
                 grid.path(invertpath$x, invertpath$y,
                           id.lengths=invertpath$id.lengths,
                           default="native",
                           gp=gpar(col="green", fill="white"))
             })


The final result is far from perfect, but I hope it might be of some help.

One issue is that most of the contour labels are obscured, though that 
might be ameliorated by filling the inverted map with a semi-transparent 
colour like rgb(1,1,1,.8).

Paul
On 15/02/13 08:58, Janesh Devkota wrote: