Skip to content
Prev 280883 / 398503 Next

overlaid filled contour plots: solved

MerryXmas() to R-help!

No one answered this query, but I found an easy solution that others may 
find useful, using a wrapper for contour() that calls contourLines()
and then replots the contours using polygon().  It could use a little 
tuning (easier way to specify fill.alpha) to make it a general extension
of contour() or perhaps incorporate the additional fill.* arguments 
directly into contour, where they probably belong.

# Add facility to fill contours in contour() and to return
#  the contourLines()

#  All arguments of contour.default commented out can be
#    passed to contour() as ...
#  fill.col is a vector of fill colors corresponding to levels.
#    if not supplied, calculate a set of transparent colors
#    based on col and fill.alpha
#  TODO:  add logic for fill.col=NULL to nothing extra, other
#    than return contourLines
#  TODO:  make fill.alpha accept a more standard 0-1 numeric

contourf <- function(
		x = seq(0, 1, length.out = nrow(z)),
     y = seq(0, 1, length.out = ncol(z)),
     z,
     nlevels = 10,
     levels = pretty(zlim, nlevels),
#    labels = NULL,
#    xlim = range(x, finite = TRUE),
#    ylim = range(y, finite = TRUE),
     zlim = range(z, finite = TRUE),
#    labcex = 0.6, drawlabels = TRUE, method = "flattest",
#    vfont, axes = TRUE, frame.plot = axes,
     col = par("fg"),
     fill.col,
     fill.alpha = "80",   # hex value for alpha transparency
#    lty = par("lty"), lwd = par("lwd"),
     add = FALSE, ...) {

	contour(x,y,z, nlevels=nlevels, levels=levels, zlim=zlim, col=col, 
add=add, ...)
	line.list <- contourLines(x, y, z, nlevels=nlevels, levels=levels)
	# contourLines returns a list of lists, each with components
	# 'level', 'x', 'y'

	if(missing(fill.col)) {
		colramp = colorRampPalette(c("white", col))
		fill.col <- paste(colramp(nlevels+1), fill.alpha, sep="")
	}
	for (i in seq_along(line.list)) {
		polygon(line.list[[i]][2:3], col=fill.col[i], border=NA)
	}
	invisible(line.list)
}


best,
-Michael
On 12/22/2011 9:54 AM, Michael Friendly wrote: