绘制载荷PCA与波数

时间:2016-01-23 01:14:44

标签: r plot ggplot2 pca

我有矩阵数据

Wavenumber 450.000000 451.00000
Sample 1.977876 1.977388 1.976533
Sample2 1.803184 1.802537 1.802181  ...
...
Sample29 1.929462 1.928509 1.927309

在读取文件csv后,我使用以下命令删除了第一行,仅用样本绘制图形。

s<- as.data.frame(t, nrow.names =1)
s.pca <- prcomp(s[-c(1),], center = TRUE, scale. = TRUE)
sd <- s.pca$sdev
loadings <- s.pca$rotation
rownames(loadings) <- colnames(s)
scores <- s.pca$x
library(ggplot2)
scores=as.data.frame(s.pca$x)
###---Plot Components PC1 and PC2
 p<- ggplot(data = scores, obs.scale = .8, var.scale = 1, show.names=TRUE,   aes(x = PC1, y = PC2, label = rownames(scores)))
 p<- p + geom_hline(yintercept = 0, colour = "gray65")
 p<- p + geom_vline(xintercept = 0, colour = "gray65")
 p<- p + geom_text(colour = "black", alpha = 0.8, size = 4)
 p<- p + ggtitle("PCA plot Samples")
 p<- p + theme(axis.title = element_text(family = "Arial", color="#666666", face="bold", size=16))
 p<- p + theme(axis.text.x = element_text(face="bold", color="#993333", size=14,angle=0))
 p<- p + theme(axis.text.y = element_text(face="bold", color="#993333", size=14, angle=0))
 p<- p + xlab("PC1")
 p<- p + ylab("PC2")
 print(p)

我删除了第一行,我想知道如何加载(PC1和PC2)与矩阵的波数?

1 个答案:

答案 0 :(得分:1)

由于我们没有您的数据,以下是使用chemometrics包中的数据的简单示例。它是分类数据,但您可以扩展示例以使用波数作为x坐标。

library("ggplot2")
library("chemometrics")
data(glass)
glass.pca <- prcomp(glass)
loadings <- as.data.frame(glass.pca$rotation)
# add in the element info:
loadings <- data.frame(element = colnames(glass), loadings)
qplot(x = element, y = PC1, data = loadings, main = "Loadings for PC1", xlab = "Compound/Element")

或者如果你想得分:

scores <- as.data.frame(glass.pca$x)
qplot(x = PC1, y = PC2, data = scores, main = "Score Plot")

编辑:使用您的数据(不是方便的形式,您应该学会使用hyperSpecChemoSpec

Wave <- read.csv("matrix.csv", nrows = 1)
Int <- read.csv("matrix.csv", skip = 1)
SampNames <- Int[,1]
Int <- Int[,-1]
Fabio <- prcomp(Int)

scores <- Fabio$x
rownames(scores) <- SampNames
scores <- as.data.frame(scores)
qplot(x = PC1, y = PC2, data = scores, geom = "point")

loadings <- Fabio$rotation
rownames(loadings) <- Wave
loadings <- cbind(wave = unlist(Wave), loadings)
loadings <- as.data.frame(loadings)
qplot(x = wave, y = PC1, data = loadings, geom = "line")