首页 > 解决方案 > PCA 双图中的着色子集

问题描述

我正在研究一个名为expression. 我的样本属于不同的子组,在 colname 中表示(即所有在 colname 中包含“adk”的样本都属于同一个子组)

       adk1  adk2  bas1  bas2  bas3  non1  ...
gene1   1.1   1.3   2.2   2.3   2.8   1.6
gene2   2.5   2.3   4.1   4.6   4.2   1.9
gene3   1.6   1.8   0.5   0.4   0.9   2.2
...

我已经使用定义了子集

adk <- expression[grepl('adk', names(expression))]

然后我使用这个数据集做了一个 PCA

pca = prcomp (t(expression), center = F, scale= F)

我现在想在 PCA 双标图中绘制我从 PCA 获得的 PC。为此,我希望属于同一子组的所有样本都具有相同的颜色(例如,所有“adk”样本应该是绿色,所有“bas”样本应该是红色,所有“非”样本应该是蓝色)。我尝试使用来自 ggfortifycolorautoplot函数的参数,但我无法让它使用我定义的子集。

如果有人可以帮助我,我会很高兴!谢谢 :)

编辑:我想给你一个我想做的例子,使用 USArrests 数据集:

head(USArrests)
           Murder Assault UrbanPop Rape
Alabama      13.2     236       58 21.2
Alaska       10.0     263       48 44.5
Arizona       8.1     294       80 31.0
Arkansas      8.8     190       50 19.5
California    9.0     276       91 40.6
Colorado      7.9     204       78 38.7

## Doing a PCA on the USArrests dataset

US.pca = prcomp(t(USArrests), center = F, scale = F)

## Now I can create a PCA biplot of PC1 and PC2 using the autoplot function (since I have ggfortify installed)

biplot1 = autoplot(US.pca,data=t(USArrests), x=1, y=2)

我希望所有在其名称中包含“e”的样本(在本例中为“Murder”和“Rape”)都是相同的颜色。“UrbanPop”和“Assault”样本也应该是单独的颜色。我希望这能让事情变得更清楚:)

PS 我在 Windows 10 上的最新版本的 RStudio 中运行 R

标签: rsubsetpca

解决方案


欢迎来到 SO!像这样的东西呢,使用ggbiplot包:

# PCA
pca <- prcomp (t(expressions), center = F, scale= F)
# first you get the vector of the names
# gr <- substr(rownames(t(expressions)),1,3)
# EDIT
gr <-gsub(".*(adk|bas|non).*$", "\\1",rownames(t(expressions)), ignore.case = TRUE)

library(ggbiplot)
# plot it
ggbiplot(pca, groups = gr)+ 
  scale_color_manual(values=c("green", "red"," blue")) + 
  theme_light()

在此处输入图像描述

编辑
如果您使用的是 R 4.0.0,您将按照以下两行安装软件包:

library(devtools)
install_github("vqv/ggbiplot", force = TRUE)

有数据:

expressions <- read.table(    text = "adk1  adk2  bas1  bas2  bas3  non1 
                               gene1   1.1   1.3   2.2   2.3   2.8   1.6
                               gene2   2.5   2.3   4.1   4.6   4.2   1.9
                               gene3   1.6   1.8   0.5   0.4   0.9   2.2", header = T )

推荐阅读