首页 > 解决方案 > 如何绘制 PCA 的前几个值

问题描述

我已经使用中等大小的数据集运行了 PCA,但我只想从该分析中可视化一定数量的点,因为它们来自重复观察,我想看看成对观察在阴谋。我已将其设置为前 18 个人是我想要绘制的人,但我似乎不能只绘制前 18 个点而不只分析前 18 个而不是整个数据集(43 人)。

# My data file
TrialsMR<-read.csv("NER_Trials_Matrix_Retrials.csv", row.names = 1)
# I ran the PCA of all of my values (without the categorical variable in col 8)
R.pca <- PCA(TrialsMR[,-8], graph = FALSE)
# When I try to plot only the first 18 individuals with this method, I get an error
fviz_pca_ind(R.pca[1:18,], 
             labelsize = 4, 
             pointsize = 1, 
             col.ind = TrialsMR$Bands, 
             palette = c("red", "blue", "black", "cyan", "magenta", "yellow", "gray", "green3", "pink" ))
# This is the error
Error in R.pca[1:18, ] : incorrect number of dimensions 

18 个人都是配对的,所以只使用 9 种颜色应该不会导致错误(我希望)。

谁能帮我绘制整个数据集的 PCA 的前 18 个点?

我的数据框在结构上看起来与此类似

TrialsMR
      Trees Bushes Shrubs Bands
JOHN1     1      4     18  BLUE
JOHN2     2      6     25  BLUE
CARL1     1      3     12 GREEN
CARL2     2      4     15 GREEN
GREG1     1      1     15   RED
GREG2     3     11     26   RED
MIKE1     1      7     19  PINK
MIKE2     1      1     25  PINK

其中每个波段对应于经过两次测试的特定个体。

标签: rpca

解决方案


您使用了错误的参数来指定个人。用于select.ind选择所需的个人,例如:

data(iris)                                                  # test data

如果您想根据特定的分组标准重命名您的行,以便在绘图中轻松识别。例如。让setosa从 1 开始串联,类似于 100-199,类似versicolor在 200-299 和virginica在 300-399。在PCA之前执行此操作。

new_series <- c(101:150, 201:250, 301:350)                # there are 50 of each 
rownames(iris) <- new_series
R.pca <- prcomp(iris[,1:4],scale. = T)                    # pca

library(factoextra)

fviz_pca_ind(X= R.pca, labelsize = 4, pointsize = 1, 
             select.ind= list(name = new_series[1:120]),  # 120 out of 150 selected
             col.ind = iris$Species ,
             palette = c("blue", "red", "green" ))

在此处输入图像描述

在使用新功能之前,请务必先参考 R 文档。

R 文档:fviz_pca {factoextra}

X
类 PCA [FactoMineR] 的对象;prcomp 和 princomp [统计数据];dudi 和 pca [ade4];expOutput/epPCA [博览会]。

select.ind, select.var
选择要绘制的个体/变量。允许的值为 NULL 或包含参数名称、cos2 或 contrib 的列表

对于您的特定虚拟数据,应该这样做:

 R.pca <- prcomp(TrailsMR[,1:3], scale. = TRUE)

 fviz_pca_ind(X= R.pca, 
              select.ind= list(name = row.names(TrialsMR)[1:4]),  # 4 out of 8
              pointsize = 1, labelsize = 4,
              col.ind = TrialsMR$Bands,
              palette = c("blue", "green" )) + ylim(-1,1)

DD PCA:试验MR

虚拟数据:

TrialsMR <- read.table( text = "Trees Bushes Shrubs Bands
JOHN1     1      4     18  BLUE
JOHN2     2      6     25  BLUE
CARL1     1      3     12 GREEN
CARL2     2      4     15 GREEN
GREG1     1      1     15   RED
GREG2     3     11     26   RED
MIKE1     1      7     19  PINK
MIKE2     1      1     25  PINK", header = TRUE)

推荐阅读