使用ggcorrplot通过分类变量绘制多个相关矩阵
我使用使用ggcorrplot通过分类变量绘制多个相关矩阵,r,ggplot2,r-corrplot,R,Ggplot2,R Corrplot,我使用ggcorrplot包和以下代码创建了一个简单的相关矩阵: library(ggcorrplot) corr <- round(cor(data[,18:24], use = "complete.obs"),2) gg <- ggcorrplot(corr) print(gg) 库(ggcorrplot) corr这可能不可能使用ggcorrplot,它将相关矩阵作为输入,并将其融合到一个合适的数据帧中,然后用于某些特定的ggplot内容以生成绘图 但是您可以使用ggcorr
ggcorrplot
包和以下代码创建了一个简单的相关矩阵:
library(ggcorrplot)
corr <- round(cor(data[,18:24], use = "complete.obs"),2)
gg <- ggcorrplot(corr)
print(gg)
库(ggcorrplot)
corr这可能不可能使用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
现在,我剪切并粘贴ggcorrplot
的相关部分,并在末尾粘贴一个facet\u 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)
谢谢您的意见。我尝试了你的代码,但不幸的是它对我不起作用。然而,我所做的是创建了两个数据帧,然后使用ggpubr/ggarrange包将所有相关矩阵包含在一个页面上。我成功地使用了这种方法,我非常感谢您向我展示重塑2软件包的熔化功能。
library(tidyverse)
library(reshape2)
my_data <- data.frame(region = factor(rep(1:6, each = 25)),
replicate(7, rnorm(6*25)))
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])))))
ggtheme = ggplot2::theme_minimal
colors = c("blue", "white", "red")
outline.color = "gray"
legend.title = "Corr"
tl.cex = 12
tl.srt = 45
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)