[R] Filled vector contours

Jan Tosovsky j.tosovsky at email.cz
Sun Aug 24 22:30:19 CEST 2014

On 2014-08-24 Prof Brian Ripley wrote:
> On 24/08/2014 08:51, Jan Tosovsky wrote:
> >
> > I am trying to create vector output (SVG) of filled contours.
> >
> > I've found two approaches so far:
> >
> > (1)
> > library('lattice')
> > svg("D:/test.svg")
> > filled.contour(volcano)
> > #levelplot(volcano, panel=panel.levelplot.raster)
> > dev.off()
> >
> > (2)
> > library("raster")
> > svg("D:/test.svg")
> > rr <- raster(t(volcano))
> > rc <- cut(rr, breaks= 10)
> > pols <- rasterToPolygons(rc, dissolve=T)
> > spplot(pols)
> > dev.off()
> >
> > But I'd like to get smooth closed polygons not broken into small
> > cells.
> How can a polygon be 'smooth'?

This was related to the result of example (2), which is more coarse
comparing it to the result of (1).

> But the region between two contours is not in general a closed polygon.

I appologize for not being precise here.

My goal is to get something like this:

which is a composition of level plots, e.g.

By 'level plot' I mean the cut of the data at certain level. It is always a
closed polygon (or multiple polygons) consisting of contour lines connected,
if required, by border lines. 

For me it is preferred way over 'isoband', which doesn't include areas
hidden by upper levels:

Please note I am not sure if this terminology (isoband, level plot, etc) is

> > Are there better methods in R ?
> Neither of those are 'in R'!
> But you could get a long way by looking at the following
> ?contourLines
> ?polygon
> ?grid::grid.polygon
> all of which are part of R.  R is a fully-fledged programming 
> language and you could write SVG directly from R: using the svg device 
> is limited by the steps to the R graphics primitives (see the 'R 
> Internals' manual) and cairographics.

Thanks a lot for detailed explanation. Now I understand it more.

Most of contouring libraries create the list of line fragments. And this
seems to be the case also of R's 'contourLines'.

But filling the areas requires a further post-processing (joining line
fragments, joining contours, set the correct direction to preserve holes).
And if I understand correctly, this is let to R 'libraries'. Unfortunately,
none of these two is optimal for my use case.

If there is any hidden option or another library (implementing e.g. Marching
squares) which could produce output similar to that linked SVG file, I am
one big ear.

Thanks, Jan

More information about the R-help mailing list