Science11
Science11

Reputation: 883

Eliminate the diagonal values in a correlation plot

I am trying to analyze the correlation between various factors using ggplot2. How do I get rid of the diagonal values that have a correlation value of 1?

Here's the code:

data(attitude)
library(ggplot2)
library(reshape2)

M = cor(attitude,use="pairwise.complete.obs")
M = round(M,4)
M[lower.tri(M)] <- NA

dat2 <- melt(M, id.var = rownames(M)[1])
ggplot(dat2, aes(as.factor(Var1), Var2, group=Var2)) + geom_tile(aes(fill = value)) + 
geom_text(aes(fill = dat2$value, label = round(dat2$value, 1))) +
scale_fill_gradient(low = "yellow", high = "#D6604D", space = "Lab", 
na.value = "grey50")

Here's the plot and my goal is to get rid of the diagonal values.

enter image description here

Upvotes: 4

Views: 2226

Answers (1)

Shawn Hemelstrand
Shawn Hemelstrand

Reputation: 3228

Here is a ggcorrplot method in case you haven't considered it before:

#### Load Additional Libraries ####
library(dplyr)
library(correlation)
library(ggcorrplot)

#### Create Correlation Matrix ####
cor.att <- attitude %>% 
  correlation()

#### Plot It ####
ggcorrplot(cor.att,
           type = "upper",
           lab = T,
           show.diag = F)

Which produces this without the diagonals using the upper triangle you wanted:

enter image description here

Upvotes: 1

Related Questions