简体   繁体   中英

How does not display the matrix diagonal data in ggplot2?

I want to plot Correlation matrix plot. like this

在此处输入图像描述

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

在此处输入图像描述

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?

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:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM