如何将两个独立的相关热图的两半挤压在一起?

时间:2019-05-03 20:50:22

标签: r ggplot2 tidyverse

对于同一组变量,我有两组数据,并且可以很容易地为它们建立一个关联热图。但是,我想将两个单独的相关热图的两个半压在一起。如果运行下面的代码,则将生成两个单独的热图,理论上它们可以在1:1线上对齐,并且顶部面板是df1的关联,底部面板是df2的关联。有什么方法可以使两个图形与网格包装功能重叠吗?还是我必须将其带入GIMP或进行整理?

library(tidyverse)
library(gridExtra)
library(reshape2)

get_upper_tri <- function(cormat){
    cormat[lower.tri(cormat)]<- NA
    return(cormat)
}

get_lower_tri <- function(cormat){
    cormat[upper.tri(cormat)]<- NA
    return(cormat)
}

df1 <- data.frame(a = rnorm(100, 10),
                  b = rnorm(100, 50),
                  c = rnorm(100, 12),
                  d = rnorm(100, 35))

cor1 <- cor(df1)

cor1 <- get_upper_tri(cor1)

p1 <- melt(cor1) %>%
  filter(is.na(value) == FALSE & value != 1) %>%
  ggplot(., aes(Var1, Var2, fill = value))+
  geom_raster()+
  scale_fill_viridis_c(guide = FALSE)+
  theme(panel.background = element_blank(),
        axis.ticks = element_blank())+
  labs(x = NULL, y = NULL)

df2 <- data.frame(a = rnorm(100, 65),
                  b = rnorm(100, 1),
                  c = rnorm(100, 1000),
                  d = rnorm(100, 500))

cor2 <- cor(df2)

cor2 <- get_lower_tri(cor2)

p1 <- melt(cor1) %>%
  filter(is.na(value) == FALSE) %>%
  ggplot(., aes(Var1, Var2, fill = value))+
  geom_raster()+
  scale_fill_viridis_c(guide = FALSE)+
  theme(panel.background = element_blank(),
        axis.ticks = element_blank())+
  labs(x = NULL, y = NULL)+
  geom_text(aes(label = round(value, 2)))

p2 <- melt(cor2) %>%
  filter(is.na(value) == FALSE) %>%
  ggplot(., aes(Var1, Var2, fill = value))+
  geom_raster()+
  scale_fill_viridis_c(guide = FALSE)+
  theme(panel.background = element_blank(),
        axis.ticks = element_blank())+
  labs(x = NULL, y = NULL)+
  geom_text(aes(label = round(value, 2)))

grid.arrange(p1, p2, ncol = 2)

1 个答案:

答案 0 :(得分:0)

为什么不合并数据?

cor_combined <- cor2
cor_combined[upper.tri(cor_combined)] <- cor1[upper.tri(cor1)]
pcombined <- melt(cor_combined) %>%
  filter(is.na(value) == FALSE) %>%
  ggplot(., aes(Var1, Var2, fill = value))+
  geom_raster()+
  scale_fill_viridis_c(guide = FALSE)+
  theme(panel.background = element_blank(),
        axis.ticks = element_blank())+
  labs(x = NULL, y = NULL)+
  geom_text(aes(label = round(value, 2)))