首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用ggcorrplot包更改相关图的对角线方向-如果类型为"upper“或"lower”

使用ggcorrplot包更改相关图的对角线方向-如果类型为"upper“或"lower”
EN

Stack Overflow用户
提问于 2021-05-14 15:15:25
回答 2查看 151关注 0票数 1

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

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

代码语言:javascript
复制
library(ggcorrplot)
data(mtcars)
corr.mat <- cor(mtcars[, c("mpg", "disp", "hp", "drat", "wt", "carb")])
ggcorrplot(corr.mat)
print(corr.mat)

给出了以下解决方案,只要您使用规范type = "full“,就可以很好地工作。然而,如果你只想显示一半的图形,它就会变得混乱:

代码语言:javascript
复制
# 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[,6:1], type = "upper")

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-05-14 15:43:43

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

代码语言:javascript
复制
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()

票数 4
EN

Stack Overflow用户

发布于 2021-05-14 15:25:29

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

代码语言:javascript
复制
ggcorr(mtcars[, c("mpg", "disp", "hp", "drat", "wt", "carb")], method = c('everything', "p"))

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67530405

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档