首页 > 解决方案 > 如何从使用 GGally 完成的相关矩阵中删除“Corr”文本?

问题描述

我已将以下代码用于相关矩阵

library(ggplot2)
library(GGally)
ggpairs(CorrelationBINA, title="Correlation matrix of BINA dhan7",
        upper = list(continuous= wrap("cor", size = 10)),
        lower = list(continuous ="smooth"))

并得到以下相关矩阵。从矩阵的上三角形中,我想删除“Corr”这个词,只保留相关值。

标签: correlationggally

解决方案


这需要一个用户定义的函数,计算相关性,四舍五入到小数点后两位,然后显示此文本而不是具有“Corr”项的相关值默认值:

#This function identifies correlation for each pair of variables that will go into ggpairs command written later

cor_func <- function(data, mapping, method, ...){
  x <- eval_data_col(data, mapping$x)
  y <- eval_data_col(data, mapping$y)
  
  corr <- cor(x, y, method=method, use='complete.obs')
  
  
  ggally_text(
    label = as.character(round(corr, 2)), 
    mapping = aes(),
    xP = 0.5, yP = 0.5,
    color = 'black',
    ...
  )
}


ggpairs(iris[-5], 
        upper = list(continuous = wrap(cor_func,
                                       method = 'spearman')))

推荐阅读