[R] Question about graphics in R

Duncan Murdoch murdoch at stats.uwo.ca
Sun Jan 8 04:06:22 CET 2006


On 1/7/2006 12:47 PM, Martin Erwig wrote:
> Considering the R function/plot shown below, I wonder whether
> it is possible to do the following changes:
> 
> (1) Change the color of each point to be picked from
> list of colors according to its z-value. (The range
> should be from blue (z=0) to red (z=1).) The grid
> should then be omitted. [I have seen "terrain.colors", but
> don't know how to use it for this purpose.]
> 
> (2) Add two lines to the surface for, say z=0.8 and
> z=0.3. [Can contour or contourLines be used?]
> 
> 
> ---
> 
> x <- seq(0, 1, length = 50)
> y <- x
> f <- function(x,y) { sin ((1-x)*y) }
> z <- outer(x,y,f)
> 
> persp(x, y, z,
> 	theta = 30, phi = 30,
> 	shade = 0.3, col = "red"
> 	)

It's not that hard, but there are a couple of tricks to it.  The 
colorRamp() and colorRampPalette() functions give you the way to go from 
z values to colors.  persp() wants output in the form colorRampPalette 
gives, so use that.

But the col option to persp() wants one color per facet, not one per z 
value, so you need to be a little careful calculating them.  However, 
this should give what you want:

colfn <- colorRampPalette(c("blue","white","red"))

# You don't need white in the middle, but I think it looks better

cols <- colfn(256)[1 + 255*z[1:49, 1:49]]

trans <- persp(x, y, z, theta=30, phi=30,  col = cols)

To add the lines, use contourLines() to calculate them, then trans3d() 
(from the ?persp examples) to convert them to coordinates that can be 
plotted.  E.g.

clines <- contourLines(x,y,z, levels=c(0.8, 0.3))

trans3d <- function(x,y,z, pmat) {
        tr <- cbind(x,y,z,1) %*% pmat
        list(x = tr[,1]/tr[,4], y= tr[,2]/tr[,4])
      }

for (i in seq(along=clines)) lines(trans3d(clines[[i]]$x, clines[[i]]$y,
  clines[[i]]$level, trans))



> ---
> 
> 
> Finally, I would also produce a flattened 2D map
> of the same function, i.e. a map in which each point
> (x,y) is mapped to a color in a range according to
> f(x,y). Also two lines for f(x,y)=c1 and f(x,y)=c2
> should be added.

Use image() for that, e.g.

image(x,y,z)

and then contour():

contour(x,y,z,levels=c(0.8,0.3),add=T)

Duncan Murdoch
> 
> Is this possible?
> 
> I would be grateful for any hints.
> 
> 
> Thanks,
> Martin
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html




More information about the R-help mailing list