Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding point and lines to 3D scatter plot in R

Tags:

r

pca

I want to visualize concentration ellipsoids in 3d scatter plot in respect of principal components (principal components as axes of these ellipsoids). I used function scatter3d with option ellipsoid = TRUE

data3d <- iris[which(iris$Species == "versicolor"), ]

library(car)
library(rgl)
scatter3d(x = data3d[,1], y = data3d[,2], z = data3d[,3],
      surface=FALSE, grid = TRUE, ellipsoid = TRUE,
      axis.col = c("black", "black", "black"), axis.scales = FALSE,
      xlab = "X1", ylab = "X2", zlab = "X3",  surface.col = "blue",
      revolution=0, ellipsoid.alpha = 0.0, level=0.7, point.col = "yellow", add=TRUE)

to draw this plot:

enter image description here

Then I was trying to add "mean point" using

points3d(mean(data3d[,1]), mean(data3d[,2]), mean(data3d[,3]), col="red", size=20)

but this point is not in the place it's supposed to be (in the center of ellipsoid): enter image description here

and I'm wondering why and how can I rescale it (?). And another question, which will arise after this how can I add axes of this ellipsoid to the plot?

like image 659
flaminka Avatar asked May 03 '15 13:05

flaminka


1 Answers

Looking at car:::scatter3d.default shows that the coordinates are internally scaled by the min and max of each dimension; the following code scales before plotting:

sc <- function(x,orig) {
    d <- diff(range(orig))
    m <- min(orig)
    (x-m)/d
}
msc <- function(x) {
    sc(mean(x),x)
}

points3d(msc(data3d[,1]),
         msc(data3d[,2]),
         msc(data3d[,3]), col="red", size=20)
like image 124
Ben Bolker Avatar answered Sep 23 '22 01:09

Ben Bolker