[R] Plot a sphere

Derick Schoonbee schoonbee at hotmail.com
Sat Dec 27 10:09:48 CET 2003


Hi,

Thank you all for the solutions.. I now have 3 ways of plotting a 'perfect' 
sphere :)

1> rgl
2> scatterplot3d
3> persp (with polygon) as below.

Personally I like the transformation solution as in 3. Thanks a mill.

Derick Schoonbee



From: David Brahm  <brahm at alum.mit.edu>
Reply-To: brahm at alum.mit.edu
To: r-help at stat.math.ethz.ch
CC: schoonbee at hotmail.com
Subject: Re: [R] Plot a sphere
Date: Fri, 26 Dec 2003 10:29:08 -0500

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