# 安装并加载必要的包
if (!require("vegan")) install.packages("vegan")
if (!require("ggplot2")) install.packages("ggplot2")
if (!require("plotly")) install.packages("plotly")
if (!require("reticulate")) install.packages("reticulate")# 加载包
library(vegan)
library(ggplot2)
library(plotly)
library(reticulate)# 设置工作目录
setwd("C:/Users/fordata/Desktop/研究生/第二个想法(16s肠型+宏基因组功能)/第二篇病毒组/result/β多样性")# 载入数据
tpm <- read.table("fetal_2.0_rpkm.txt", header = TRUE, row.names = 1)
tpm <- t(tpm)
metadata <- read.table("fetal_2.0_metadata.txt", header = TRUE, row.names = 1)
metadata$group <- as.factor(metadata$group)# 计算 Bray-Curtis 距离矩阵
dist_matrix <- vegdist(tpm, method = "bray")# 执行 NMDS 分析
nmds_result <- metaMDS(dist_matrix, k = 3, trymax = 200) # 增加 trymax 的值# 提取NMDS的坐标得分(提取样本点的坐标)
scores_nmds <- as.data.frame(nmds_result$points)
colnames(scores_nmds) <- c("NMDS1", "NMDS2", "NMDS3")# 将元数据添加到结果中
df_nmds <- cbind(scores_nmds, metadata)# 查看列名 (确保有 NMDS1, NMDS2, NMDS3)
colnames(df_nmds)# 绘制3D NMDS图
fig <- plot_ly(df_nmds, x = ~NMDS1, y = ~NMDS2, z = ~NMDS3, color = ~group, colors = c("AF" = "#BD3C29", "M" = "#0172B6", "P" = "#78D3AC", "UB"="#E18727", "NC"="black"),type = 'scatter3d', mode = 'markers', marker = list(size = 13)) %>%layout(scene = list(xaxis = list(title = "NMDS1"),yaxis = list(title = "NMDS2"),zaxis = list(title = "NMDS3")),legend = list(x = 1, y = 0.5, font = list(size = 16))) # 调整图例位置# 显示图形
fig# 计算组间差异的PERMANOVA分析
adonis_result <- adonis2(dist_matrix ~ group, data = metadata, permutations = 999)
cat("PERMANOVA结果:\n")
print(adonis_result)# 计算组间差异的ANOSIM分析
anosim_result <- anosim(dist_matrix, metadata$group, permutations = 999)
cat("\nANOSIM结果:\n")
print(anosim_result)# 保存为高分辨率 PDF
# 使用外部工具或 `orca` 保存为 PDF(例如需要安装 `orca` 工具)
# fig %>% save_image("fetal_nmds_3d_plot.pdf", width = 800, height = 600, scale = 2)
保存图片是个问题,我试了一下,export出html文件,然后到网页截图会比较清楚
- PERMANOVA 结果(通过
adonis2()
计算):你将会得到组间差异的 R² 值、F 值以及 p 值。p 值越低,组间差异越显著。 - ANOSIM 结果(通过
anosim()
计算):你将会得到组间相似性的 R 值和相应的 p 值。R 值越接近 1,组间差异越大;R 值越接近 0,说明组内和组间的差异相似。