2016-10-28 17 views
0

在生成一個包含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) 

我應該如何正確繪製和着色這個主成分分析?謝謝。

+0

你可以提供創建當前情節你的代碼? – BLT

+0

@BLT這不需要是一個雙觸點(可能有更好的方式來繪製它),但下面是我試過的代碼:'biplot(pca,scale = 0,col = c(「orange」,「紅色「,」藍色「))' – Kyle

+0

這是否適用於您的真實數據? http://rpubs.com/sinhrks/plot_pca – BLT

回答

2

如果我正確理解你的問題,ggparcoordGally包會幫助你。

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)) 

不過,我認爲它更有意義做PCA上x而不是xymatrix包括目標y。所以下面的代碼應該更適合你的情況。

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)) 
1

下面是一個基本的R解決方案,以顯示如何簡單地做到這一點。首先僅對x矩陣執行主成分分析,並從結果對象中獲得變換後的變量矩陣,我們將其稱爲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") 

enter image description here

相關問題