How to build a perfectly circular sphere in R (rgl.spheres)

R has a great function for plotting spheres (see below). However, the sphere is not round, but looks very sharp when scaled. How can I build a perfectly circular sphere? Thank! Cheers, Chris

library(rgl)

rgl.spheres(1,1,1,radius=1,color="blue")

      

+3


source to share


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







All Articles