使用 ggcorrplot 包更改相关图对角线的方向 - 如果输入“upper”或“lower”

Poz*_*oza 1 r correlation ggcorrplot

我对这里的问题还有一个后续问题。

This person wanted to make a correlation plot with ggcorrplot from the package ggcorrplot. However, they wanted to have the diagonal going down the matrix instead of up from left to right. So, they wanted to make the graph look like the correlation matrix that they used as input:

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

The following solution was given, which works fine, as long as you use the specification type = "full". However, if you just want to show half of the graph, it gets messed up:

# 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")
Run Code Online (Sandbox Code Playgroud)

Does anyone know how to make that upper correlogram with the diagonal going from top-left to bottom-right?

mt1*_*022 5

您可以使用以下方式绘制 corr.matgeom_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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述