Skip to content
Prev 22301 / 398503 Next

What does persp() return?

I seem to recall this coming up before (I'm on a slow link so will not 
check the mailing list archives), but here is a bit of hackery for adding 
points and lines (etc.) to a persp() plot.  Of course, it doesn't do 
hidden line removal ...

## matrix multiply c(3dv,1) by transformation matrix:
## plot v[0]/v[3], v[1]/v[3]

x <- seq(-10, 10, length = 50)
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
par(bg = "white")
trans3d <- function(x,y,z,pmat) {
  tmat <- t((cbind(x,y,z,1)%*% pmat))
  list(x=tmat[1,]/tmat[4,],y=tmat[2,]/tmat[4,])
}

pmat <- persp(x, y, z, theta = 30, phi = 30, expand = 0.5, 
              col = "lightblue", xlab = "X", ylab = "Y", zlab = "Z",
              ticktype="detailed")
m <- 1e-5
points(trans3d(m,m,f(m,m),pmat),pch=16)
z2 <- sapply(1:length(x),function(n)f(x[n],y[n]))
lines(trans3d(x,y,z2,pmat),col="red",lwd=2)
lines(trans3d(c(-10,10,10,-10,-10),
              c(-10,-10,10,10,-10),
              c(2,2,8,8,2),pmat),col="blue")
On Thu, 1 Aug 2002, David Brahm wrote: