Marc in the box Marc in the box - 1 year ago 133
R Question

How does one turn contour lines into filled contours?

Does anyone know of a way to turn the output of

polygons in order to plot as filled contours, as with
. Is there an order to how the polygons must then be plotted in order to see all available levels? Here is an example snippet of code that doesn't work:

#typical plot
filled.contour(volcano, color.palette = terrain.colors)

cont <- contourLines(volcano)
fun <- function(x) x$level
LEVS <- sort(unique(unlist(lapply(cont, fun))))
COLS <- terrain.colors(length(LEVS))
for(i in seq(cont)){
COLNUM <- match(cont[[i]]$level, LEVS)
polygon(cont[[i]], col=COLS[COLNUM], border="NA")
contour(volcano, add=TRUE)

enter image description here

Answer Source

A solution that uses the raster package (which calls rgeos and sp). The output is a SpatialPolygonsDataFrame that will cover every value in your grid:

rr <- raster(t(volcano))
rc <- cut(rr, breaks= 10)
pols <- rasterToPolygons(rc, dissolve=T)

Here's a discussion that will show you how to simplify ('prettify') the resulting polygons.

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download