Mar*_*sen 2 r ggplot2 pca vegan
我还是 R 的新手,正在尝试学习如何使用库 vegan,我可以使用普通的 plot 函数轻松地在 R 中绘图。当我想在 ggplot 中绘制数据时出现问题。我知道我必须从我创建的列表中提取正确的数据,但是哪些以及如何提取?我一直在练习的数据集可以在这里下载https://drive.google.com/file/d/0B1PQGov60aoudVR3dVZBX1VKaHc/view?usp=sharing 我一直用来转换数据的代码是这样的:
library(vegan)
library(dplyr)
library(ggplot2)
library(grid)
data <- read.csv(file = "People.csv", header = T, sep = ",", dec = ".", check.names = F, na.strings=c("NA", "-", "?"))
data2 <- data[,-1]
rownames(data2) <- data[,1]
data2 <- scale(data2, center = T, scale = apply(data2, 2, sd))
data2.pca <- rda(data2)
Run Code Online (Sandbox Code Playgroud)
这给了我一个列表,我可以使用基本的“plot”和“biplot”函数进行绘制,但我不知道如何在 ggplot 中绘制 PCA 和 biplot。我还想按组为数据点着色,例如性别。任何帮助都会很棒。
您可以为此使用我的ggvegan包。尽管可用于某些类别的对象,包括rda和对象,但它仍在开发中cca。
假设示例数据和分析,您可以简单地执行以下操作:
autoplot(data2.pca, arrows = TRUE)
Run Code Online (Sandbox Code Playgroud)
得到你想要的那种双标图。这产生
您可以通过以下方式获取站点标签
autoplot(data2.pca, arrows = TRUE, geom = "text", legend = "none")
Run Code Online (Sandbox Code Playgroud)
它还显示了如何在需要时抑制图例(legend.position采用适合ggplot2 中相同主题元素的值)。
你不会有一个巨大的控制其他的东西一起关注一下量autoplot()的方法(还),但是你可以用fortify()获得数据的方式GGPLOT2需要它,然后从其他的答案使用的想法或学习的代码ggvegan:::autoplot.rda为具体。
您需要从 github安装ggvegan,因为该软件包尚未在 CRAN 上:
install.packages("devtools")
devtools::install_github("gavinsimpson/ggvegan")
Run Code Online (Sandbox Code Playgroud)
这将为您提供 0.0-6(或更高版本)版本,其中包括一些小调整以生成比以前版本更整洁的图。
ggbiplot(...)package 中有一个函数ggbiplot,但它仅适用于 prcomp、princomp、PCA 或 lda 类的对象。
plot.rda(...)只是将每个案例(人)定位在 PC1 - PC2 空间中。biplot.rda(...)将向量添加到原始数据集中每个变量的 PC1 和 PC2 载荷。事实证明plot.rda(...),并biplot.rda(...)使用通过汇总 rda 对象产生的数据,而不是 rda 对象本身。
smry <- summary(data2.pca)
df1 <- data.frame(smry$sites[,1:2]) # PC1 and PC2
df2 <- data.frame(smry$species[,1:2]) # loadings for PC1 and PC2
rda.plot <- ggplot(df1, aes(x=PC1, y=PC2)) +
geom_text(aes(label=rownames(df1)),size=4) +
geom_hline(yintercept=0, linetype="dotted") +
geom_vline(xintercept=0, linetype="dotted") +
coord_fixed()
rda.plot
Run Code Online (Sandbox Code Playgroud)
rda.biplot <- rda.plot +
geom_segment(data=df2, aes(x=0, xend=PC1, y=0, yend=PC2),
color="red", arrow=arrow(length=unit(0.01,"npc"))) +
geom_text(data=df2,
aes(x=PC1,y=PC2,label=rownames(df2),
hjust=0.5*(1-sign(PC1)),vjust=0.5*(1-sign(PC2))),
color="red", size=4)
rda.biplot
Run Code Online (Sandbox Code Playgroud)
如果您将这些结果与 进行比较plot(data2.pca),biplot(data2.pca)我想您会发现它们是相同的。不管你相信与否,到目前为止,最困难的部分是让文本与箭头正确对齐。