我使用ggcorrplot包和以下代码创建了一个简单的相关矩阵:
library(ggcorrplot)
corr <- round(cor(data[,18:24], use = "complete.obs"),2)
gg <- ggcorrplot(corr)
print(gg)我现在想做的是使用相同的数据创建多个相关矩阵,但使用一个称为"region“(列位置为”5“)的分类变量将其分开:类似于使用facet_wrap函数。但是,当我尝试这样做时,我得到了一个错误。我尝试过以下几种方法:
library(ggcorrplot)
corr <- round(cor(data[,18:24], use = "complete.obs"),2)
gg <- ggcorrplot(corr) +
facet_wrap("region", ncol = 2)
print(gg)我得到的错误是"Error in combine_vars(data, params$plot_env, vars, drop = params$drop) : At least one layer must contain all variables used for facetting"
我知道'corr‘不是指"region“字段,我想知道如何才能做到这一点。因此,基本上,输出将是由“区域”分隔的6个相关矩阵,而不是所有数据的一个相关矩阵。
发布于 2018-04-06 01:08:58
使用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)

https://stackoverflow.com/questions/49676516
复制相似问题