如何用ggplot2绘制ade4包mantel.rtest的Mantel检验结果?
嘿,这个问题我熟!ade4里的mantel.rtest返回的是专属类对象,没法直接转成data.frame,但咱们手动把需要的核心数据抠出来就行,用ggplot2画图完全没问题。下面是具体的解决方法:
用ggplot2绘制Mantel检验结果的步骤
首先先运行你的示例代码得到检验结果对象r1(记得提前加载需要的包):
library(ade4) library(ggplot2) data(yanomama) gen <- quasieuclid(as.dist(yanomama$gen)) geo <- quasieuclid(as.dist(yanomama$geo)) r1 <- mantel.rtest(geo, gen)
1. 提取并整理数据
mantel.rtest的结果对象本质是一个列表,我们需要的核心数据都藏在里面:
r1$obs:观测到的Mantel相关系数r1$sim:置换检验生成的模拟相关系数分布r1$pvalue:检验的p值
我们把模拟数据转成data.frame,同时单独提取观测值和p值方便后续标注:
# 将模拟统计量转换为data.frame mantel_df <- data.frame(simulated_r = r1$sim) # 提取关键指标 observed_r <- r1$obs p_value <- r1$pvalue
2. 用ggplot2绘制自定义图
你可以选择直方图或者密度图来展示置换分布,再添加观测值的标记和关键指标标注:
直方图版本(直观展示频数)
ggplot(mantel_df, aes(x = simulated_r)) + geom_histogram(bins = 30, fill = "#69b3a2", color = "white", alpha = 0.8) + # 用红色虚线标出观测到的相关系数 geom_vline(xintercept = observed_r, color = "#e74c3c", linewidth = 1.2, linetype = "dashed") + # 添加观测值和p值的文本标注 annotate("text", x = observed_r + 0.1, y = max(table(cut(mantel_df$simulated_r, 30))), label = paste0("Observed r = ", round(observed_r, 3), "\np-value = ", round(p_value, 3)), hjust = 0, color = "#e74c3c", fontface = "bold") + labs(title = "Mantel's Test: Genetic vs Geographic Distance", x = "Simulated Mantel Correlation Coefficient", y = "Frequency") + theme_minimal()
密度图版本(更平滑的分布展示)
ggplot(mantel_df, aes(x = simulated_r)) + geom_density(fill = "#69b3a2", alpha = 0.7) + geom_vline(xintercept = observed_r, color = "#e74c3c", linewidth = 1.2, linetype = "dashed") + annotate("text", x = observed_r + 0.1, y = max(density(mantel_df$simulated_r)$y), label = paste0("Observed r = ", round(observed_r, 3), "\np-value = ", round(p_value, 3)), hjust = 0, color = "#e74c3c", fontface = "bold") + labs(title = "Mantel's Test: Genetic vs Geographic Distance", x = "Simulated Mantel Correlation Coefficient", y = "Density") + theme_minimal()
原理说明
mantel.rtest返回的mantelrtest类对象虽然不能直接转成data.frame,但它本质是一个包含多个元素的列表。我们直接访问列表里的sim、obs等元素,就能拿到ggplot2需要的结构化数据,进而完全自定义绘图的样式、颜色、标注等,比基础的plot()函数灵活太多啦。
内容的提问来源于stack exchange,提问作者i.b
相关产品推荐
相关产品推荐

