Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize ggcorrplot

Tags:

r

ggplot2

I want to reduce the size of markers in ggcorrplot, and reduce the space between text and the plot.

library(ggcorrplot)
data(mtcars)

corr <- round(cor(mtcars), 1)
ggcorrplot(corr,sig.level=0.05 ,lab_size = 4.5, p.mat = NULL, insig = c("pch", "blank"), pch = 1, pch.col = "black", pch.cex =1,
  tl.cex = 14)
like image 685
Geo-sp Avatar asked Dec 21 '16 18:12

Geo-sp


1 Answers

You can adjust the distance between the axis text and the plot with theme elements. With geom_tile in a standard ggplot, you can adjust the height and width of the tiles. ggcorrplot doesn't seem to accept that adjustment. There may be a way I'm not aware of; I haven't used the package before. My hacky workaround is to just overlay a white grid to create space between the tiles:

ggcorrplot(corr, sig.level=0.05, lab_size = 4.5, p.mat = NULL, 
           insig = c("pch", "blank"), pch = 1, pch.col = "black", pch.cex =1,
           tl.cex = 14) +
  theme(axis.text.x = element_text(margin=margin(-2,0,0,0)),  # Order: top, right, bottom, left
        axis.text.y = element_text(margin=margin(0,-2,0,0))) +
  geom_vline(xintercept=1:ncol(mtcars)-0.5, colour="white", size=2) +
  geom_hline(yintercept=1:ncol(mtcars)-0.5, colour="white", size=2) 

enter image description here

This type of plot is also not that difficult to make as a regular ggplot, and then you'll have full control over the plot elements:

library(reshape2)   

ggplot(melt(corr), aes(Var1, Var2, fill=value)) +
  geom_tile(height=0.8, width=0.8) +
  scale_fill_gradient2(low="blue", mid="white", high="red") +
  theme_minimal() +
  coord_equal() +
  labs(x="",y="",fill="Corr") +
  theme(axis.text.x=element_text(size=13, angle=45, vjust=1, hjust=1, 
                                 margin=margin(-3,0,0,0)),
        axis.text.y=element_text(size=13, margin=margin(0,-3,0,0)),
        panel.grid.major=element_blank()) 

enter image description here

Another hack with ggcorrplot is to cover up and then redraw the tiles using geom_tile so that we can access the height and width arguments:

ggcorrplot(corr, sig.level=0.05, lab_size = 4.5, p.mat = NULL,
           insig = c("pch", "blank"), pch = 1, pch.col = "black", pch.cex =1,
           tl.cex = 14) +
  theme(axis.text.x = element_text(margin=margin(-2,0,0,0)),
        axis.text.y = element_text(margin=margin(0,-2,0,0)),
        panel.grid.minor = element_line(size=10)) + 
  geom_tile(fill="white") +
  geom_tile(height=0.8, width=0.8)

enter image description here

like image 196
eipi10 Avatar answered Sep 19 '22 15:09

eipi10