昨天在明哥的公众号【小明的数据分析笔记本】上看到了他正在探讨一幅相关性矩阵图。
这幅图其实就是通过Mantel test检验统计,可视化环境变量矩阵(如pH,有机碳,总氮,盐度等)与物种/功能丰度矩阵之间的相关性 。
拿到一个陌生的图,第一步肯定得查查看是否有文献来源
。于是,我用百度/谷歌识图
搜索了一下,好家伙,不搜不知道,一搜吓一跳,19年Science发表过类似的图片后,各路大神都在复现,甚至还开发了专门的R包。
既然有现成的包,那咱也不客气了,直接拿来用就是了。
安装 ggcor
# Gitee地址安装(试了好几个)
devtools::install_git("https://gitee.com/dr_yingli/ggcor")
library(ggcor)
library(ggplot2)
相关性图
# 以mtcars 数据集为例
# 不同的图形代码如下
library(patchwork)
# layer of tile
A <- quickcor(mtcars) + geom_colour()
# layer of circle and trim the lower triangle
B <- quickcor(mtcars, type = "upper") + geom_circle2()
# layer of ellipse and not show diagonal
C <- quickcor(mtcars, type = "lower", show.diag = FALSE) + geom_ellipse2()
# layer of square and reorder correlation matrix by cluster
D <- quickcor(mtcars, cluster = TRUE) + geom_square()
# layer of confidence box
E <- quickcor(mtcars, cor.test = TRUE) + geom_confbox()
# different layer of upper/lower triangle
F <- quickcor(mtcars, cor.test = TRUE) +
geom_square(data = get_data(type = "lower", show.diag = FALSE)) +
geom_mark(data = get_data(type = "upper", show.diag = FALSE)) +
geom_abline(slope = -1, intercept = 12)
(A+B+C)/(E+D+F)+ plot_annotation(tag_levels = 'A')
组合相关性图
library(dplyr)
library(vegan)
library(ggplot2)
# 载入示例数据
data("varechem", package = "vegan")
data("varespec", package = "vegan")
# Mantel.test 检验计算矩阵相关性
mantel <- mantel_test(varespec, varechem, mantel.fun = 'mantel.randtest',spec.dist.method = 'bray', env.dist.method = 'euclidean',
spec.select = list(Spec01 = 1:7,
Spec02 = 8:18,
Spec03 = 19:37
)) %>%
mutate(r_value = cut(r, breaks = c(-Inf, 0.25, 0.5, Inf),
labels = c('<0.25', '0.25-0.5', '>=0.5'), right = FALSE),
p_value = cut(p.value, breaks = c(-Inf, 0.001, 0.01, 0.05, Inf),
labels = c('<0.001', '0.001-0.01', '0.01-0.05', '>=0.05'), right = FALSE))
quickcor(varechem, type = "upper") +
geom_square() +
anno_link(aes(colour = p_value, size = r_value), data = mantel) +
scale_size_manual(values = c(0.5, 1, 2)) +
scale_colour_manual(values = c("#D95F02", "#1B9E77", "#A2A2A288")) +
guides(size = guide_legend(title = "Mantel's r",
override.aes = list(colour = "grey35"),
order = 2),
colour = guide_legend(title = "Mantel's p",
override.aes = list(size = 3),
order = 1),
fill = guide_colorbar(title = "Pearson's r", order = 3))
环状热图
# 需要安装ambient包
install.packages('ambient')
library(ambient)
rand_correlate(100, 8) %>% ## require ambient packages
quickcor(circular = TRUE, cluster = TRUE, open = 45) +
geom_colour(colour = "white", size = 0.125) +
anno_row_tree() +
anno_col_tree() +
set_p_xaxis() +
set_p_yaxis()