I would like to use ggplot2
to make an upper triangle correlation matrix like this one. I can replicate that one just fine, but for some reason I'm stuck on really wanting to convert the reshape2
functions to tidyr
ones. I would think that I could use gather
in place of melt
, but that is not working.
Original Results using reshape2
library(reshape2)
library(ggplot2)
mydata <- mtcars[, c(1,3,4,5,6,7)]
cormat <- round(cor(mydata),2)
library(reshape2)
melted_cormat <- melt(cormat)
# Get upper triangle of the correlation matrix
get_upper_tri <- function(cormat){
cormat[lower.tri(cormat)]<- NA
return(cormat)
}
upper_tri <- get_upper_tri(cormat)
melted_cormat <- melt(upper_tri, na.rm = TRUE)
ggplot(data = melted_cormat, aes(Var2, Var1, fill = value)) +
geom_tile()
My attempt at this using gather
from tidyr
.
library(tidyverse)
#first correlatoin matrix
cor_base <- round(cor(mydata), 2)
#now UT
cor_base[lower.tri(cor_base)] <- NA
cor_tri <- as.data.frame(cor_base) %>%
rownames_to_column("Var2") %>%
gather(key = Var1, value = value, -Var2, na.rm = TRUE) %>%
as.data.frame()
ggplot(data = cor_tri, aes(x = Var2, y = Var1, fill = value)) +
geom_tile()
The values are all the same, but some change in order occurred that is making this look wrong. A check of identical
doesn't return TRUE
but the values of the two data frames seem to be the same...
> identical(cor_tri, melted_cormat)
[1] FALSE
> dim(cor_tri)
[1] 21 3
> dim(melted_cormat)
[1] 21 3
> sum(cor_tri == melted_cormat)
[1] 63
Any thoughts on this or should I just go ahead and load reshape2
to accomplish what I'm going for?
Thanks.