[R] Plot contour inside a polygon

Duncan Murdoch murdoch at stats.uwo.ca
Fri Mar 20 13:56:13 CET 2009


On 3/20/2009 8:40 AM, Irina Foss wrote:
> Dear,
> 
> I am trying to plot contours (with filled.contour function) inside UK area, so that no contours are plotted over the sea. I was wondering if anyone can help me with this task and if I can get any suggestions how to do that.


If you have a grid of values over a larger area than the UK, set the 
values outside the UK to NA, then contour won't draw contours there.

For example, to get contours only in the circle x^2 + y^2 < 1:

x <- seq(-1, 1, len=100)
y <- seq(-1, 1, len=100)
z <- outer(x, y, function(x,y) ifelse(x^2 + y^2 < 1, sin(x)+cos(y), NA))
contour(x,y,z)

theta <- seq(0, 2*pi, len=256)
lines(cos(theta), sin(theta))

The maps package contains map.where() to say what region a particular 
grid point is in; just check that it's a UK region.

Duncan Murdoch




More information about the R-help mailing list