使用ggcorrplot 可能无法做到这一点,它将相关矩阵作为其输入并将其融合到合适的数据帧中,然后用于某些特定的ggplot 内容以制作绘图。
但是您可以使用ggcorrplot 源代码来获得您想要的。
作为初步步骤,让我们看一下“融化”的相关矩阵。
(small_cor <- cor(replicate(2, rnorm(25))))
#> [,1] [,2]
#> [1,] 1.00000000 0.06064063
#> [2,] 0.06064063 1.00000000
(reshape2::melt(small_cor))
#> Var1 Var2 value
#> 1 1 1 1.00000000
#> 2 2 1 0.06064063
#> 3 1 2 0.06064063
#> 4 2 2 1.00000000
它是相关矩阵的数据框版本,其中每一行是来自原始数据的变量组合的相关性。
现在我们将着手处理一些示例数据。有 6 个区域和 7 个变量。
library(tidyverse)
library(reshape2)
my_data <- data.frame(region = factor(rep(1:6, each = 25)),
replicate(7, rnorm(6*25)))
我们需要融合了区域 ID 的相关矩阵。这就是我的做法。可能有更好的方法。我认为这可能是您必须做的最棘手的事情。
my_cors <- cbind(region = factor(rep(levels(my_data$region), each = 7^2)),
do.call(rbind, lapply(split(my_data, my_data$region), function(x) melt(cor(x[,-1])))))
现在我将从ggcorrplot 源代码复制并粘贴。首先,从参数列表中粘贴以获得一些默认值:
ggtheme = ggplot2::theme_minimal
colors = c("blue", "white", "red")
outline.color = "gray"
legend.title = "Corr"
tl.cex = 12
tl.srt = 45
现在我剪切并粘贴ggcorrplot 的相关部分并在最后粘贴facet_wrap 以获得您想要的。
my_cors %>%
ggplot(aes(Var1, Var2, fill = value)) +
geom_tile(color = outline.color) +
scale_fill_gradient2(low = colors[1],
high = colors[3],
mid = colors[2],
midpoint = 0,
limit = c(-1, 1),
space = "Lab",
name = legend.title) +
ggtheme() + theme(axis.text.x = element_text(angle = tl.srt,
vjust = 1,
size = tl.cex, hjust = 1),
axis.text.y = ggplot2::element_text(size = tl.cex)) +
coord_fixed() +
facet_wrap("region", ncol=2)