2
votes

I want to plot a correlation plot with ggpairs, of which the upper display the correlation coefficient and the lower panel display the correlated dotplot. And all these panel will be filled with color by the correlation coefficient. My code is like this:

###data matrix with sample name
df = data.frame(matrix(data = rexp(200, rate = 0.1), nrow = 20, ncol = 10)) %>%
  `colnames<-`(paste("sample",1:10,sep = ""))

###main plot
p1 = df %>%
  ggpairs(.,lower = list(continuous = wrap("points", size=0.1)),
          upper = list(continuous = wrap("cor", method = "spearman",size= 2)))

###color panel
p2 = df %>% 
  ggcorr(., method = c("everything", "spearman"),
            low = "blue",mid="white",high = "red",limits = c(-1, 1),midpoint = 0,
            label = TRUE,label_round = 2,label_size = 2)
  
###get color 
p = 10
g2 <- ggplotGrob(p2)
colors <- g2$grobs[[6]]$children[[3]]$gp$fill

# Change background color to tiles in the upper and lower triangular matrix of plots 
idx <- 1
for (k1 in 1:(p-1)) {
  for (k2 in (k1+1):p) {
    plt <- getPlot(p1,k1,k2) +
      theme_bw()+theme(panel.background = element_rect(fill=colors[idx],colour = NA),
                       panel.grid.major = element_blank(),
                       panel.grid.minor = element_blank(),
                       plot.background = element_rect(fill=colors[idx],colour = NA))
    p1 <- putPlot(p1,plt,k1,k2)
    idx <- idx+1
  }
}

### lower
idx <- 1
for (k1 in 1:(p-1)) {
  for (k2 in (k1+1):p) {
    plt <- getPlot(p1,k2,k1) +
      theme_bw()+theme(panel.background = element_rect(fill=colors[idx],colour = NA),
                       panel.grid.major = element_blank(),
                       panel.grid.minor = element_blank(),
                       plot.background = element_rect(fill=colors[idx],colour = NA))
    p1 <- putPlot(p1,plt,k2,k1)
    idx <- idx+1
  }
}

###plot
library(grid)
p1+theme(panel.spacing = unit(0, "lines"),
         axis.text.x = element_blank(),
         axis.ticks = element_blank(),
         axis.text.y = element_blank())

the final plot is like this: enter image description here

However, I want to show the sample name in the ggpair-diag panel instead of the upper or lower panel lab, how to do this? In addition, is there any solution to remove the redundant "corr" text in the upper panel?

1

1 Answers

1
votes

Add axisLabels = "internal" to your code:

p1 = df %>%
  ggpairs(.,lower = list(continuous = wrap("points", size=0.1)),
          upper = list(continuous = wrap("cor", method = "spearman",size= 2)), axisLabels = "internal")

To remove the "Corr" text from the upper diagonal refer to here