我想用R做PCA
我的数据有10,000列和90行,我使用prcomp函数来执行PCA.试图用prcomp结果准备一个双标图,我遇到了10,000个绘制的向量覆盖我的数据点的问题.双标图是否有任何隐藏向量表示的选项?
要么
我可以用它plot来获得PCA结果.但我不确定如何根据我的数据点标记这些点,数据点编号为1到90.
Sample<-read.table(file.choose(),header=F,sep="\t")
Sample.scaled<-data.frame(apply(Sample_2XY,2,scale))
Sample_scaled.2<-data.frame(t(na.omit(t(Sample_2XY.scaled))))
pca.Sample<-prcomp(Sample_2XY.scaled.2,retx=TRUE)
pdf("Sample_plot.pdf")
plot(pca.Sample$x)
dev.off()
Run Code Online (Sandbox Code Playgroud)
如果您执行help(prcomp)或?prcomp,则帮助文件会告诉我们prcomp()函数返回的对象中包含的所有内容.我们只需要选择我们想要绘制的内容,并使用一些能够让我们更多控制的功能来完成它biplot().
对于帮助文件没有说明事情的情况,更常见的技巧是str()在prcomp对象(在你的情况下是pca.Sample)上查看它的所有部分并找到我们想要的东西(str()紧凑地显示R的内部结构)对象.)
以下是R的一些示例数据的示例:
# do a pca of arrests in different states
p<-prcomp(USArrests, scale = TRUE)
Run Code Online (Sandbox Code Playgroud)
str(p)给了我一些丑陋和太长的东西,但我可以看到p $ x的状态为rownames,它们在主要组件上的位置为列.有了这个,我们可以按照我们想要的方式绘制它,例如with plot()和text()(对于标签):
# plot and add labels
plot(p$x[,1],p$x[,2])
text(p$x[,1],p$x[,2],labels=rownames(p$x))
Run Code Online (Sandbox Code Playgroud)
如果我们使用许多观察值制作散点图,则标签可能无法读取.因此,我们可能只希望标记更多极端值,我们可以通过以下方式识别quantile():
#make a new dataframe with the info from p we want to plot
df <- data.frame(PC1=p$x[,1],PC2=p$x[,2],labels=rownames(p$x))
#make sure labels are not factors, so we can easily reassign them
df$labels <- as.character(df$labels)
# use quantile() to identify which ones are within 25-75 percentile on both
# PC and blank their labels out
df[ df$PC1 > quantile(df$PC1)["25%"] &
df$PC1 < quantile(df$PC1)["75%"] &
df$PC2 > quantile(df$PC2)["25%"] &
df$PC2 < quantile(df$PC2)["75%"],]$labels <- ""
# plot
plot(df$PC1,df$PC2)
text(df$PC1,df$PC2,labels=df$labels)
Run Code Online (Sandbox Code Playgroud)