我有一个关于one 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[,6:1], type = "upper")有人知道如何制作从左上角到右下角的对角线上的相关图吗?
发布于 2021-05-14 15:43:43
您可以使用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()

发布于 2021-05-14 15:25:29
当我只想显示相关矩阵的一半时,我使用这个(来自GGally包):
ggcorr(mtcars[, c("mpg", "disp", "hp", "drat", "wt", "carb")], method = c('everything', "p"))然而,对角线并不是你想要的。也许有一个选项可以反转它。
https://stackoverflow.com/questions/67530405
复制相似问题