Search code examples
rggplot2ggcorrplot

Superscript and subscript labels on correlation matrix using ggcorrplot


I am trying to customize the labels on a correlation matrix made using the ggcorrplot package. However, I cannot get the superscript or subscript formatting to work. How can I get the labels to display properly without using Unicode characters?

library(tidyverse)
library(ggcorrplot)

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

# Attempt 1: Not formatted correctly
colnames(M) <- c("Temperature\n (^o C)", "PO[4]^2", "Oxygen\n (mg L^-1)")
rownames(M) <- c("Temperature\n (^o C)", "PO[4]^2", "Oxygen\n (mg L^-1)")

ggcorrplot(M,
           type = "lower",
           lab = TRUE,
           ggtheme = theme_bw())


# Attempt 2: Produces error message
ggcorrplot(M,
           type = "lower",
           lab = TRUE,
           scale_x_discrete(labels = c("mpg" = expression(Temperature~(degree*C)),
                                       "cyl" = expression(PO[4]^2),
                                       "disp" = expression(Oxygen~(mg~L^-1)))),
           scale_y_discrete(labels = c("mpg" = expression(Temperature~(degree*C)),
                                       "cyl" = expression(PO[4]^2),
                                       "disp" = expression(Oxygen~(mg~L^-1)))),
           ggtheme = theme_bw())
#> Error in match.arg(method): 'arg' must be NULL or a character vector

Created on 2024-04-23 with reprex v2.1.0


Solution

  • An option with ggtext using markdown formatting:

    library(tidyverse)
    library(ggcorrplot)
    library(ggtext)
    
    M <- cor(mtcars)[1:3,1:3]
    
    colnames(M) <- c("Temperature<br> (<sup>o</sup> C)", "PO<sub>4</sub><sup>2</sup>", "Oxygen<br> (mg L<sup>-1</sup>)")
    rownames(M) <- c("Temperature<br> (<sup>o</sup> C)", "PO<sub>4</sub><sup>2</sup>", "Oxygen<br> (mg L<sup>-1</sup>)")
    
    ggcorrplot(M,
               type = "lower",
               lab = TRUE,
               ggtheme = theme_bw()) +
      theme(axis.text = element_markdown())
    

    Created on 2024-04-23 with reprex v2.1.0