微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 ggcorrplot 包更改相关图对角线的方向 - 如果键入“上”或“下”

如何解决使用 ggcorrplot 包更改相关图对角线的方向 - 如果键入“上”或“下”

我有一个关于 here 的后续问题。

此人想用 ggcorrplot 包中的 ggcorrplot 制作相关图。然而,他们想让对角线沿着矩阵向下而不是从左到右向上。因此,他们想让图表看起来像他们用作输入的相关矩阵:

library(ggcorrplot)
data(mtcars)
corr.mat <- cor(mtcars[,c("mpg","disp","hp","drat","wt","carb")])
ggcorrplot(corr.mat)
print(corr.mat)

给出了以下解决方案,只要您使用规范 type = "full",就可以正常工作。然而,如果你只想显示一半的图形,它就会搞砸:

# This suggested solution works fine:
ggcorrplot(corr.mat[,6:1])
# The same: 
ggcorrplot(corr.mat[,6:1],type = "full")

# Here we have the problem:
ggcorrplot(corr.mat[,type = "upper")

有谁知道如何用从左上角到右下角的对角线制作上相关图?

解决方法

您可以使用 geom_tile 手动绘制 corr.mat:

library(data.table)
library(ggplot2)
cordt <- as.data.table(corr.mat,keep.rownames = 'col_name')
cordt <- melt(cordt,id.vars = 'col_name',variable.name = 'row_name')

# convert to factor so that rows and columns have the same order as the data
cordt[,row_name := factor(row_name,levels = rev(rownames(corr.mat)))]
cordt[,col_name := factor(col_name,levels = rownames(corr.mat))]

# set diagonal and the top-right half of the matrix to 0 so that those cells appears white
cordt[ncol(corr.mat) - as.integer(row_name) < as.integer(col_name),value := 0]
# remove the last column and the bottom row (where left cells are self correlations only)
cordt <- cordt[as.integer(row_name) < ncol(corr.mat) &
        as.integer(col_name) < ncol(corr.mat)]

ggplot(cordt,aes(x = col_name,y = row_name,fill = value)) +
    geom_tile() +
    scale_fill_gradient2(low = 'blue',high = 'red') +
    labs(x = NULL,y = NULL,fill = 'Corr') +
    theme_minimal()

enter image description here

,

当我只想显示相关矩阵的一半时,我使用它(来自 GGally 包):

ggcorr(mtcars[,c("mpg","disp","hp","drat","wt","carb")],method = c('everything',"p"))

然而,对角线并不是你想要的。 也许有一个选项可以反转它

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。