rggplot2ggcorrplot

Adjust axis label placement on ggcorrplot


How can I get the y-axis label to plot next to the correlation square? The default is to place all labels on the same axis however, I would like them to be offset.

The script below has the y-axis labels stacked. I would like the top row label cyl to be next to the red tile with a value of 0.9.

library(ggplot2)
library(ggcorrplot)

# Example Data
M <- cor(mtcars)[1:3,1:3]

ggcorrplot(M,
           type = "lower",
           outline.color = 'black',
           lab = TRUE,
           tl.srt = 0,
           ggtheme = ggplot2::theme_void)

Created on 2025-05-12 with reprex v2.1.1

The ideal output would look similar to this: enter image description here

A similar SO question was asked years ago: Changing position of labels in ggcorrplot


Solution

  • You can turn off the y axis labels and add a geom_text layer containing calculated label positions from your correlation matrix. It also requires turning clipping off:

    library(tidyverse)
    library(ggcorrplot)
    
    M <- cor(mtcars)[1:3, 1:3]
    
    labs <- tibble(label = rev(head(row.names(M), -1)), 
                   x = rev(seq(label)) - 0.6,
                   y = rev(seq(label)))
    
    ggcorrplot(M,
               type = "lower",
               outline.color = 'black',
               lab = TRUE,
               tl.srt = 0,
               ggtheme = ggplot2::theme_void) +
      scale_y_discrete(labels = NULL) +
      geom_text(aes(label = label, x = x, y = y), data = labs, 
                inherit.aes = FALSE, hjust = 1) +
      coord_equal(clip = "off")
    

    enter image description here

    If we change M to M <- cor(mtcars) the same code gives us:

    enter image description here