Rosie
Rosie

Reputation: 21

How does not display the matrix diagonal data in ggplot2?

I want to plot Correlation matrix plot. like this

enter image description here

so, I generated a matrix data and ploted in R. but, I got a strange picture.

enter image description here

this is my code.

aa1=data.frame(eada=c(1.1,5,0,0,0,0),
              goke=c(2.2,5,0,0,0,0),
              adet=c(1.0,5,0,0,0,0),
              feag=c(2.3,5,0,0,0,0),
              edep=c(2.5,5,0,0,0,0),
              jate=c(1.5,7,0,0,0,0),
              pafe=c(2.6,8,0,0,0,0),
              bink=c(3.3,6,0,0,0,0),
              culp=c(2.1,6,0,0,0,0),
              soit=c(1.3,6,0,0,0,0),
              yosp=c(2.1,5,0,0,0,0),
              wiso=c(2.3,8,0,0,0,0))

as.data.frame(lapply(aa1,as.numeric))
cormat1=round(cor(aa1),2)

# Get lower triangle of the correlation matrix
get_lower_tri<-function(cormat1){
    cormat1[upper.tri(cormat1)] <- NA
    return(cormat1)}

lower_tri <- get_lower_tri(cormat1)
t(lower_tri)

melted_cormat1 <- melt(lower_tri, na.rm = TRUE)

ggplot(melted_cormat1, aes(Var2, Var1, fill = value))+
 geom_tile(color = "white")+
  scale_x_discrete(position = "top") +
 scale_fill_gradient2(low = "#8134af", high = "#C00000", mid = "white") +
  theme_bw()

I want to solve the questions:

  1. The position of the figure is in the lower left corner;
  2. Don't display the matrix diagonal data in picture.
  3. If I want the background of the other colors(such as black), do I need plot a picture before painting correlation matrix plot?

Upvotes: 0

Views: 549

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173858

To answer your questions in the order you asked them:

  1. You need to reverse the order of the y axis variables to get the lower corner to contain your tiles. You can do this by making Var2 a factor, then using its reverse levels for the levels when you factor Var1:
melted_cormat1$Var2 <- factor(melted_cormat1$Var2)
melted_cormat1$Var1 <- factor(melted_cormat1$Var1, rev(levels(melted_cormat1$Var2)))
  1. To remove the matrix diagonal, remove all the rows from melted_cormat1 where Var1 == Var2
melted_cormat2 <- melted_cormat1[which(melted_cormat1$Var1 != melted_cormat1$Var2),]
  1. To plot with a black panel background, use theme(panel.background = element_rect(fill = "black")):
ggplot(melted_cormat2, aes(Var2, Var1, fill = value)) +
  geom_tile(color = "white")+
  scale_x_discrete(position = "top") +
  scale_fill_gradient2(low = "#8134af", high = "#C00000", mid = "white") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "black"),
        panel.grid = element_blank())

Which results in:

enter image description here

Upvotes: 1

Related Questions