3

R has a great function to plot spheres (see below). However, the sphere is not round, but looks edgy when zooming in. How can I plot a perfectly round sphere? Thank you! Cheers, Chris

library(rgl)

rgl.spheres(1,1,1,radius=1,color="blue")
David Arenburg
  • 91,361
  • 17
  • 137
  • 196

1 Answers1

2

The function below is an imitation of rgl.spheres. ng is number of grids on the sphere. if you increase the 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))
Sezen
  • 447
  • 1
  • 5
  • 17