R :NMDS(第二版)
rm (list = ls ())#清除所有变量
setwd("C:\\Users\\Administrator\\Desktop\\NMDS\\Fun") #设置工作目录
# 1. 导入所需的库。
library(vegan)
library(ggplot2)
# 2. 定义所需的函数。
mydata <- read.delim("mydata.txt", header = TRUE, sep = "\t")
mygroups <- read.delim("mygroup.txt", header = TRUE, sep = "\t")
# 计算bray_curtis距离
distance <- vegdist(mydata[, -1], method = 'bray') # 排除SampleID列
# NMDS排序分析
nmds <- metaMDS(distance, k = 2)
# 获得应力值(stress)
stress <- nmds$stress
# 将绘图数据转化为数据框
df <- as.data.frame(nmds$points)
# 与分组数据合并
df$SampleID <- rownames(df)
df <- merge(df, mygroups, by = "SampleID")
# 设置随机种子
set.seed(123)
# 基于bray-curtis距离进行PERMANOVA分析
adonis <- adonis2(as.dist(distance) ~ Group, data = df, permutations = 999)
# 应力值、Adonis R2与显著性、Anosim R与显著性
stress_text <- paste("Stress =", round(stress, 4))
adonis_text <- paste("Adonis:R^2 = =", round(adonis$R2[1], 2), " P_value =", adonis$`Pr(>F)`[1])
title <- paste(stress_text, " ", adonis_text)
colors <- c("B73_Week4"="#00BFFF","B73_Week6"="#00BFFF","B73_Week8"="#00BFFF","B73_Week10"="#00BFFF","Mo17_Week4"="#FF4500","Mo17_Week6"="#FF4500","Mo17_Week8"="#FF4500","Mo17_Week10"="#FF4500")
# 定义了颜色和形状的映射关系,用于后续的可视化。
shapes <- c("B73_Week4"=24, "B73_Week6"=22, "B73_Week8"=21, "B73_Week10"=23,
"Mo17_Week4"=24, "Mo17_Week6"=22, "Mo17_Week8"=21, "Mo17_Week10"=23)
levels_order <- c("B73_Week4", "B73_Week6", "B73_Week8", "B73_Week10", "Mo17_Week4", "Mo17_Week6", "Mo17_Week8", "Mo17_Week10") #定义顺序
df$Group <- factor(df$Group, levels = levels_order)
p1 <- ggplot(df, aes(x = MDS1, y = MDS2, fill = Group, shape = Group)) + #创建了一个ggplot对象,设置了数据框points作为数据,设置了x和y作为x轴和y轴的变量,设置了Group作为填充色和形状的变量。
geom_point(alpha = .7, size = 5) + #添加了散点图层。alpha = .7设置了点的透明度,size = 5设置了点的大小。
scale_shape_manual(values = shapes) + # 设置了形状和填充色的映射关系。使用了之前定义的shapes和colors变量。
scale_fill_manual(values = colors) +
labs(x = paste("NMDS 1", sep = ""),
y = paste("NMDS 2", sep = ""), title = title) +
#设置了x轴、y轴和标题的标签。使用了paste函数将多个字符串连接在一起,使用了format函数将数字格式化为指定的小数位数。
geom_mark_ellipse(aes(fill = Group, label = Group), alpha = 0.1, color = "grey", linetype = 3) +
#添加了椭圆图层。每个椭圆代表一个组的样本,椭圆的位置和大小由组的样本的均值和标准差决定。
theme_bw() +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.text = element_text(color = "black", size = 9))
#设置了图的主题。你使用了黑白主题,并且移除了网格线,设置了坐标轴文本的颜色和大小。
# 显示绘制的图
p1
# 使用ggsave保存PCoA图为PNG格式
ggsave(filename = "NMDS_plot2.png", plot = p1, width = 12, height = 10, units = "in", dpi = 600)