I have run a principal components analysis and created a 3D scatter plot of the first 3 principal components.
I want to add ellipsoids around the data points based on the pop (population) they originate from. I can only manage to get one ellipsoid around all the data points and not separate ellipsoids for each pop.
#Load packages ####
library(plotly)
library(readxl)
library(adegenet)
library(pca3d)
#Load data and perform Discriminant Analysis of Principal Components (DAPC) ####
GenePop <- read.genepop("E:\\UNIVERSITY\\Masters\\Data\\Genetic\\Analysis\\R\\PCA.gen")
PCA <- dapc(GenePop)
#Extract the principal components and group labels ####
Components <- PCA[["tab"]]
Components <- data.frame(Components)
Components$PCA.pc.1 <- -Components$PCA.pc.1
Components$PCA.pc.2 <- -Components$PCA.pc.2
Components$PCA.pc.3 <- -Components$PCA.pc.3
Components$Pop <- PCA$grp
Components = cbind(Components)
#Create a 3D scatter plot ####
ellipse <- ellipse3d(cov(cbind(Components$PCA.pc.1, Components$PCA.pc.2, Components$PCA.pc.3)))
fig <- plot_ly(Components, x = ~PCA.pc.1, y = ~PCA.pc.2, z = ~PCA.pc.3, color = ~Pop, colors = funky(23)) %>% add_markers(size = 12) %>%
add_trace(x=ellipse$vb [1,], y=ellipse$vb [2,], z=ellipse$vb [3,], type='mesh3d', alphahull = 0, opacity = 0.01)
fig <- fig %>% layout(scene = list(xaxis = list(title = 'PCA1'),
yaxis = list(title = 'PCA2'),
zaxis = list(title = 'PCA3')))
fig <- fig %>% layout(scene = list(bgcolor = "white"))
fig
This is what my code currently generates 3D scatter plot. There is only 1 ellipsoid surrounding all the data and not separate ellipsoids around each pop. Here are 2 examples of what I am trying to achieve Example 1, Example 2.