Search code examples
r3dnearest-neighborrgl

"Ball" cover for one group in 3d plot


I have data containing 3 dimensions.

I calculated nearest neighbors within a radius of specific data point (using nn2)

Then, I plotted 3d plot of my data (using plot3d from rgl library):

plot3d(dfrm[1:3], col=rainbow(2)[dfrm$col], size...)

So, I have 3 colored plot:

  • 1st color- my data point

  • 2nd color- point within the radius

  • 3rd color- rest of the points

Is there a way to cover my 1st and 2nd color groups with a transparent "ball"?


Solution

  • Use the spheres3d() function to draw a sphere. You need to specify the center (presumably your data point) and radius. Use something like col = "black", alpha = 0.2 to make it transparent, and aspect = "iso" in the plot3d() call so it's not rescaled. For example,

    xyz <- matrix(rnorm(30), ncol=3)
    dist <- apply(xyz, 1, function(pt) sqrt(sum((pt - xyz[1,])^2)))
    radius <- 1
    plot3d(xyz, col=c("black", ifelse(dist[-1] < radius, "green", "red")),
           aspect = "iso", size = 3)
    spheres3d(xyz[1,,drop=FALSE], col="black", alpha = 0.2, radius=radius)
    

    which gives

    enter image description here

    The green points are inside the sphere, the red ones are outside it.