How to build a perfectly circular sphere in R (rgl.spheres)
1 answer
The function below is imitation rgl.spheres
. ng
- the number of grids on the sphere. if you increase ng
, you have more round sphere.
rgl.sphere <- function (x, y=NULL, z=NULL, ng=50, radius = 1, color="white", add=F, ...) {
lat <- matrix(seq(90, -90, len = ng)*pi/180, ng, ng, byrow = TRUE)
long <- matrix(seq(-180, 180, len = ng)*pi/180, ng, ng)
vertex <- rgl:::rgl.vertex(x, y, z)
nvertex <- rgl:::rgl.nvertex(vertex)
radius <- rbind(vertex, rgl:::rgl.attr(radius, nvertex))[4,]
color <- rbind(vertex, rgl:::rgl.attr(color, nvertex))[4,]
for(i in 1:nvertex) {
add2 <- if(!add) i>1 else T
x <- vertex[1,i] + radius[i]*cos(lat)*cos(long)
y <- vertex[2,i] + radius[i]*cos(lat)*sin(long)
z <- vertex[3,i] + radius[i]*sin(lat)
persp3d(x, y, z, specular="white", add=add2, color=color[i], ...)
}
}
to test the function:
rgl.sphere(rnorm(10), rnorm(10), rnorm(10), radius = runif(10), color = rainbow(10))
+2
source to share