[R] How to color a region in a contour plot with the contour being the boundary?

Marius Hofert marius.hofert at math.ethz.ch
Sat Dec 31 12:02:22 CET 2011


Dear expeRts,

I would like to color a certain region in a levelplot. The region for z <= 0.02 should have a dark gray color. Below is a minimal example. It almost does what I want, but The region between z=0.02 and z=1 is also colored in dark gray (instead of just the region for z <= 0.02).
How can I solve this?

Cheers,

Marius


## z values for given x and y
f <- function(x) 4*((1-x)^(-1/2)-1)
eps <- 1e-12
x <- y <- seq(eps, 1-eps, length.out=500)
z <- outer(x, y, FUN=function(x, y) pmax(f(x) + f(y) - 10, 0))

## determine colors
zcols <- c(gray(0.2), gray(seq(0.5, 1, length.out=50)), rep("#FFFFFF", max(z)-51)) # colors with dark gray in the beginning for z <= 0.02 and many whites for z > 50

## trial 1
pdf(file="levelplot1.pdf", width=6, height=6)
image(x, y, z, xaxs="r", yaxs="r", col=zcols)
contour(x, y, z, levels=c(0.02, 1, 5, 10, 20, 50, 500), add=TRUE)
dev.off()

## trial 2
pdf(file="levelplot2.pdf", width=6, height=6)
image(x, y, z, xaxs="r", yaxs="r", col=zcols, oldstyle=TRUE)
contour(x, y, z, levels=c(0.02, 1, 5, 10, 20, 50, 500), add=TRUE)
dev.off()



More information about the R-help mailing list