I’m having issues with plotly: essentially, I’ve been plotting PCA data and I need to plot them in 3D. Hence, plotly which supports that. I can plot the scores without any issues, the problem is when I try to overlap the ellipses around it to better identify the classes. Whatever I do, they never fit.
These are the two matrixes with some dummy loadings, the true PCA is computed with other methods I’m gonna skip over because it’s not the issue.
PC1 <- c(1.43, 1.20, 0.48, 0.95, -2.76, -2.53, 2.38, 6.37)
PC2 <- c (-1.46, -2.85, -2.08, -2.08, -1.50, -2.15, 0.87, -4.64)
PC3 <- c (0.08, 5.37, 1.39, 2.74, 0.06, 1.95, 0.90, -0.18)
CA <- data.frame(PC1, PC2, PC3)
PC1 <- c(40.12, 19.01, 20.63, 20.50, 30.39, 10.46, 9.07)
PC2 <- c(-2.47, -2.04, -0.46, -2.37, -0.39, 0.97, 0.15)
PC3 <- c(1.27, 1.75, 0.53, 1.16, 0.44, 1.79, -0.76)
CB <- data.frame(PC1, PC2, PC3)
library(plotly)
library(rgl)
ellipseA <- ellipse3d(cov(CA))
ellipseB <- ellipse3d(cov(CB))
fig <- plot_ly()%>%
add_trace(data = CA, x = CA[,1], y = CA[,2], z = CA[,3],
type = "scatter3d", mode = 'markers', marker = list(size = 3),
text = rownames(CA))%>%
add_trace(x=ellipseA$vb [1,], y=ellipseA$vb [2,], z=ellipseA$vb [3,],
type='mesh3d', alphahull = 0, opacity = 0.2)%>%
add_trace(data = CB, x = CB[,1], y = CB[,2], z = CB[,3],
type = "scatter3d", mode = 'markers', marker = list(size = 3),
text = rownames(CB))%>%
add_trace(x=ellipseB$vb [1,], y=ellipseB$vb [2,], z=ellipseB$vb [3,],
type='mesh3d', alphahull = 0, opacity = 0.2)
fig
the code works, in the sense that it plots a 3d scatter plot and then overlaps with two ellipses. These ellipses are nowhere near close to fit the data because they are centered on c(0,0,0) which is not the case for these data.
I also need to figure out how to change ellipses color, in order to match the color of the scatter plot but that’s a separate issue.
So far I’ve tried to twink the code, I also tried computing the ellipses separately with
fit <- lm(PC2 ~ PC3 + PC4, CA)
for example and then plotting said ellipses, but it does nothing worthy