I have a follow-up question to the one here.
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)
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")
Does anyone know how to make that upper correlogram with the diagonal going from top-left to bottom-right?
You can plot corr.mat with geom_tile
manually:
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()