【问题标题】:Plotting two principal component score vectors, using a different color to indicate three unique classes绘制两个主成分得分向量,使用不同的颜色来表示三个唯一的类
【发布时间】:2016-10-28 00:06:53
【问题描述】:

在生成一个模拟数据集后,在三个类别中的每个类别中包含 20 个观察值(即总共 60 个观察值)和 50 个变量,我需要绘制前两个主成分得分向量,使用不同的颜色来表示三个唯一的类。

我相信我可以创建模拟数据集(请验证),但我在弄清楚如何为类和绘图着色时遇到问题。我需要确保三个类在图中分开显示(否则我需要重新运行模拟数据)。

#for the response variable y (60 values - 3 classes 1,2,3  - 20 observations per class)
y <- rep(c(1,2,3),20)

#matrix of 50 variables i.e. 50 columns and 60 rows i.e. 60x50 dimensions (=3000 table cells)   
x <- matrix( rnorm(3000), ncol=50)

xymatrix <- cbind(y,x)
dim(x)
[1] 60 50
dim(xymatrix)
[1] 60 51
pca=prcomp(xymatrix, scale=TRUE)

如上所述,我应该如何正确绘制和着色这个主成分分析?谢谢你。

【问题讨论】:

  • 你能提供创建当前情节的代码吗?
  • @BLT 这绝不需要是双标图(可能有更好的方法来绘制它),但下面是我尝试过的代码:biplot(pca, scale=0, col=c("orange", "red", "blue"))
  • 这适用于您的真实数据吗? rpubs.com/sinhrks/plot_pca
  • @BLT 我可以得到下面的第一个代码来绘制,但我不确定如何让三个类的颜色不同(即所有点都是橙色)autoplot(pca, colour = "orange") 此代码不起作用: autoplot(pca, colour = c("orange", "red", "blue"))

标签: r plot pca


【解决方案1】:

如果我正确理解您的问题,Gally 包中的ggparcoord 会为您提供帮助。

library(GGally)
y <- rep(c(1,2,3), 20)

# matrix of 50 variables i.e. 50 columns and 60 rows 
# i.e. 60x50 dimensions (=3000 table cells)   
x <- matrix(rnorm(3000), ncol=50)

xymatrix <- cbind(y,x)
pca <- prcomp(xymatrix, scale=TRUE)

# Principal components score and group label 'y'
pc_label <- data.frame(pca$x, y=as.factor(y))

# Plot the first two principal component scores of each samples
ggparcoord(data=pc_label, columns=1:2, groupColumn=ncol(pc_label))

但是,我认为在 x 上执行 PCA 比在包含目标 yxymatrix 上更有意义。所以下面的代码应该更适合你的情况。

pca <- prcomp(x, scale=TRUE)

pc_label <- data.frame(pca$x, y=as.factor(y))

ggparcoord(data=pc_label, columns=1:2, groupColumn=ncol(pc_label))

如果您想要前两个主成分分数的散点图,您可以使用ggplot

library(ggplot2)

ggplot(data=pc_label) + 
  geom_point(aes(x=PC1, y=PC2, colour=y))

【讨论】:

    【解决方案2】:

    这是一个基本的 R 解决方案,展示了如何简单地做到这一点。首先仅对 x 矩阵进行 PCA,然后从结果对象中获取转换后变量的矩阵,我们将其称为 PCs

    x <- matrix(rnorm(3000), ncol=50)
    pca <- prcomp(x, scale=TRUE)
    PCs <- as.matrix(pca$x)
    

    现在我们可以根据您的 y 为标签制作颜色名称向量。

    col.labs <- rep(c("Green", "Blue", "Red"), 20)
    

    现在只需绘制散点图,将颜色矢量传递给col

    plot(PCs[, 1], PCs[, 2], col=col.labs, pch=19, xlab = "Scores on PC1", ylab="Scores on PC2")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-23
      • 2020-11-08
      • 1970-01-01
      • 1970-01-01
      • 2012-02-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      相关资源
      最近更新 更多