【问题标题】:R GGally::ggpairs, corrlation matrix plot, how to custom diagR GGally::ggpairs,相关矩阵图,如何自定义诊断
【发布时间】:2020-11-21 23:29:56
【问题描述】:

我想用 ggpairs 绘制相关图,其中上部显示相关系数,下部面板显示相关点图。所有这些面板都将通过相关系数填充颜色。我的代码是这样的:

###data matrix with sample name
df = data.frame(matrix(data = rexp(200, rate = 0.1), nrow = 20, ncol = 10)) %>%
  `colnames<-`(paste("sample",1:10,sep = ""))

###main plot
p1 = df %>%
  ggpairs(.,lower = list(continuous = wrap("points", size=0.1)),
          upper = list(continuous = wrap("cor", method = "spearman",size= 2)))

###color panel
p2 = df %>% 
  ggcorr(., method = c("everything", "spearman"),
            low = "blue",mid="white",high = "red",limits = c(-1, 1),midpoint = 0,
            label = TRUE,label_round = 2,label_size = 2)
  
###get color 
p = 10
g2 <- ggplotGrob(p2)
colors <- g2$grobs[[6]]$children[[3]]$gp$fill

# Change background color to tiles in the upper and lower triangular matrix of plots 
idx <- 1
for (k1 in 1:(p-1)) {
  for (k2 in (k1+1):p) {
    plt <- getPlot(p1,k1,k2) +
      theme_bw()+theme(panel.background = element_rect(fill=colors[idx],colour = NA),
                       panel.grid.major = element_blank(),
                       panel.grid.minor = element_blank(),
                       plot.background = element_rect(fill=colors[idx],colour = NA))
    p1 <- putPlot(p1,plt,k1,k2)
    idx <- idx+1
  }
}

### lower
idx <- 1
for (k1 in 1:(p-1)) {
  for (k2 in (k1+1):p) {
    plt <- getPlot(p1,k2,k1) +
      theme_bw()+theme(panel.background = element_rect(fill=colors[idx],colour = NA),
                       panel.grid.major = element_blank(),
                       panel.grid.minor = element_blank(),
                       plot.background = element_rect(fill=colors[idx],colour = NA))
    p1 <- putPlot(p1,plt,k2,k1)
    idx <- idx+1
  }
}

###plot
library(grid)
p1+theme(panel.spacing = unit(0, "lines"),
         axis.text.x = element_blank(),
         axis.ticks = element_blank(),
         axis.text.y = element_blank())

最后的情节是这样的:

但是,我想在 ggpair-diag 面板中显示样品名称,而不是在上面板或下面板实验室中,如何做到这一点? 另外,有没有什么办法可以去掉上面板多余的“corr”文字?

【问题讨论】:

    标签: r ggplot2 correlation ggally


    【解决方案1】:

    将axisLabels = "internal" 添加到您的代码中:

    p1 = df %>%
      ggpairs(.,lower = list(continuous = wrap("points", size=0.1)),
              upper = list(continuous = wrap("cor", method = "spearman",size= 2)), axisLabels = "internal")
    

    要从上对角线上删除“Corr”文本,请参阅here

    【讨论】:

      猜你喜欢
      • 2015-08-31
      • 1970-01-01
      • 1970-01-01
      • 2015-05-06
      • 1970-01-01
      • 2021-11-18
      • 2013-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多