[R] Plot a sphere
David Brahm
brahm at alum.mit.edu
Fri Dec 26 16:29:08 CET 2003
Derick Schoonbee <schoonbee at hotmail.com> wrote:
> Would somebody please be so kind as to direct me in plotting a 3D sphere?
Here's one way. I generate an empty 3D plot with "persp", then fill it with
polygons transformed with "trans3d" (as found in the help for "persp"). I
didn't do hidden surface removal (you didn't mention whether you wanted it),
but if you do, just reorder the polygons from "back" to "front" and paint them
a solid color (e.g. col="red"), so hidden ones get painted over.
pmat <- persp(0:1, 0:1, matrix(,2,2), xlim=c(-1,1), ylim=c(-1,1), zlim=c(-1,1),
theta=25, phi=30, expand=.9, xlab="X", ylab="Y", zlab="Z")
trans3d <- function(x,y,z, pmat) { # From the help for "persp"
tr <- cbind(x,y,z,1) %*% pmat
list(x = tr[,1]/tr[,4], y= tr[,2]/tr[,4])
}
theta <- seq(0, 2*pi, length=51)
phi <- seq(0, pi, length=26)
x <- cos(theta) %o% sin(phi)
y <- sin(theta) %o% sin(phi)
z <- rep(1, length(theta)) %o% cos(phi)
for (j in seq(phi)[-1]) for (i in seq(theta)[-1]) {
idx <- rbind(c(i-1,j-1), c(i,j-1), c(i,j), c(i-1,j))
polygon(trans3d(x[idx], y[idx], z[idx], pmat))
}
--
-- David Brahm (brahm at alum.mit.edu)
More information about the R-help
mailing list