# [R] 3d plot with different levels done in different colors (solution)

Tamas Papp tpapp at axelero.hu
Sat Jul 12 13:20:51 CEST 2003

```On Fri, Jul 11, 2003 at 01:49:37PM -0700,

I finally managed to do what I originally wanted. I would like to
thank the help I received from Jerome Asselin and Peter Dalgaard. Here
it is:

levelpersp <- function(x, y, z, colors=topo.colors, ...) {
## getting the value of the midpoint
zz <- (z[-1,-1] + z[-1,-ncol(z)] + z[-nrow(z),-1] + z[-nrow(z),-ncol(z)])/4
## calculating the breaks
breaks <- hist(zz, plot=FALSE)\$breaks
## cutting up zz
cols <- colors(length(breaks)-1)
zzz <- cut(zz, breaks=breaks, labels=cols)
## plotting
persp(x, y, z, col=as.character(zzz), ...)
## return breaks and colors for the legend
list(breaks=breaks, colors=cols)
}

## Example
x <- seq(-10, 10, length=60)
y <- x
f <- function(x,y) { r <- sqrt(x^2+y^2); 10 * sin(r)/r }
z <- outer(x, y, f)
levelpersp(x, y, z, theta = 30, phi = 30, expand = 0.5)

Regards,

Tamas

>
> Hi,
>
> Consider this example which I have modified from the persp() help file.
> It uses topo.colors() to create a series of colors.
>
> Cheers,
> Jerome
>
>      x <- seq(-10, 10, length= 30)
>      y <- x
>      f <- function(x,y) { r <- sqrt(x^2+y^2); 10 * sin(r)/r }
>      z <- outer(x, y, f)
>      z[is.na(z)] <- 1
>      op <- par(bg = "white")
>      zz <- (z[-1,-1] + z[-1,-ncol(z)] + z[-nrow(z),-1] +
>               z[-nrow(z),-ncol(z)])/4
>      cols <- topo.colors(length(zz))
>      cols[order(zz)] <- cols
>      persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = cols)
>
>
> On July 11, 2003 08:26 am, Tamas Papp wrote:
> > Content-Length: 1223
> > Status: R
> > X-Status: N
> >
> > I would like a 3d plot of a matrix such that individual trapezoids
> > that make up the surface are colored according to the z-value of that
> > point (or preferably the midpoint of its four corners, or something
> > similar). MS Excel has something like that.
> >
> > I know that persp can have an nx by ny matrix its "col" argument, I
> > just don't know how to generate that matrix. To calculate the midpoint
> > of the tiles for the matrix z, I could use something like
> >
> > zz <- (z[-1,-1] + z[-1,-nrow(z)] + z[-ncol(z),-1] +
> > z[-ncol(z),-nrow(z)])/4
> >
> > but I don't know how to assign a color to that value. For example if I
> > have
> >
> > boundaries <- c(0, .5, 1, 1.5)
> >
> > and
> >
> > colors <- c("red", "green", "blue")
> >
> > I am looking for a function that assigns red to the elements of zz
> > between 0 and .5, etc. Alternative solutions are welcome, maybe
> > somebody has already wrote a library that does the whole thing neatly.
> >
> > Thanks,
> >
> > Tamas
>

--
Tamás K. Papp
E-mail: tpapp at axelero.hu (preferred, especially for large messages)
tpapp at westel900.net
Please try to send only (latin-2) plain text, not HTML or other garbage.

```