图中的3D Biplot - R.

时间:2017-06-06 15:15:45

标签: r 3d plotly pca

我想使用plotly包构建一个3D PCA双图,因为图形很好,并且以html格式交互(我需要的东西)。

我的困难是添加装载。我希望加载从点(0,0,0)呈现为直线(即相当于2D双点)

总而言之,我不知道如何从3D图形的中心开始添加直线。

我使用PCA函数计算了分数和加载量;

pca1 <- PCA (dat1, graph = F)
分数为

ind1 <- pca1$ind$coord[,1:3]
x <- ind1[,1] ; y <- ind1[,2] ; z <- ind1[,3]

用于加载:

var1 <- pca1$var$coord[,1:3]
xl <- var1[,1] ; yl <- var1[,2] ; zl <- var1[,3]

并使用下面的代码生成3D得分图;

p <- plot_ly( x=x, y=y, z=z, 
 marker = list(opacity = 0.7, color=y  , colorscale = c('#FFE1A1', '#683531'), showscale = F)) %>% 
  layout(title = "3D Prefmap",
         scene = list(
           xaxis = list(title = "PC 1"), 
           yaxis = list(title = "PC 2"), 
           zaxis = list(title = "PC 3")))

1 个答案:

答案 0 :(得分:1)

以下是一些可用于开发3D双标图的想法。

# Data generating process
library(MASS)
set.seed(6543)
n <- 500
mu <- c(1,-2,3,-1,3,4)
Sigma <- diag(rep(1,length(mu)))
Sigma[3,1] <- Sigma[1,3] <- 0.1
Sigma[4,6] <- Sigma[6,4] <- 0.1
X <- as.data.frame(mvrnorm(n, mu=mu, Sigma=Sigma))

# PCA
pca <- princomp(X, scores=T, cor=T)

# Scores
scores <- pca$scores
x <- scores[,1]
y <- scores[,2]
z <- scores[,3]

# Loadings
loads <- pca$loadings

# Scale factor for loadings
scale.loads <- 5

# 3D plot
library(plotly)
p <- plot_ly() %>%
  add_trace(x=x, y=y, z=z,
            type="scatter3d", mode="markers",
            marker = list(color=y, 
               colorscale = c("#FFE1A1", "#683531"), 
               opacity = 0.7)) 

for (k in 1:nrow(loads)) {
   x <- c(0, loads[k,1])*scale.loads
   y <- c(0, loads[k,2])*scale.loads
   z <- c(0, loads[k,3])*scale.loads
   p <- p %>% add_trace(x=x, y=y, z=z,
            type="scatter3d", mode="lines",
            line = list(width=8),
            opacity = 1) 
}
print(p)

enter image description here