Search code examples
rmatrixggplot2pearson-correlationggcorrplot

Reorder axis labels of correlation matrix plot


I am using ggcorrplot to build a correlation matrix, but the output reorders the columns in a way that I don't want. How do I reorder the columns?

For the purposes of this example, I'll be using the 'mtcars' dataset found in R. After the final output is produced, I need to reorder the columns, because it keeps reordering to a format that I don't want.

Note: Code is provided from the website as follows: http://www.sthda.com/english/wiki/ggplot2-quick-correlation-matrix-heatmap-r-software-and-data-visualization

library(ggcorrplot)

mydata <- mtcars

#correlation matrix
cormat <- round(cor(mydata),2)

library(reshape2)
melted_cormat <- melt(cormat)
head(melted_cormat)

library(ggplot2)
ggplot(data = melted_cormat, aes(x=Var1, y=Var2, fill=value)) + 
  geom_tile()

# Get upper triangle of the correlation matrix
get_upper_tri <- function(cormat){
  cormat[lower.tri(cormat)]<- NA
  return(cormat)
}

upper_tri <- get_upper_tri(cormat)

# Melt the correlation matrix
library(reshape2)
melted_cormat <- melt(upper_tri, na.rm = TRUE)
# Heatmap
library(ggplot2)
ggplot(data = melted_cormat, aes(Var2, Var1, fill = value))+
  geom_tile(color = "white")+
  scale_fill_gradient2(low = "blue", high = "red", mid = "white", 
                       midpoint = 0, limit = c(-1,1), space = "Lab", 
                       name="Pearson\nCorrelation") +
  theme_minimal()+ 
  theme(axis.text.x = element_text(angle = 45, vjust = 1, 
                                   size = 12, hjust = 1))+
  coord_fixed()

This is the correlation matrix that I want, but I need to reorder the columns into an order different than the one shown.

Any help would be great. Thanks everyone!


Solution

  • Let's assume we want the x-axis to be ordered based on its names (labels) alphabetically and y-axis the same but in reverse order. The following code works (rest of the code will be the same).

    ggplot(data = melted_cormat, aes(reorder(Var2,  -desc(as.character(Var2))), 
                                     reorder(Var1,  desc(as.character(Var1))), fill = value))+
      geom_tile(color = "white")+
      scale_fill_gradient2(low = "blue", high = "red", mid = "white", 
                           midpoint = 0, limit = c(-1,1), space = "Lab", 
                           name="Pearson\nCorrelation") +
      theme_minimal()+ 
      theme(axis.text.x = element_text(angle = 45, vjust = 1, 
                                       size = 12, hjust = 1))+
      coord_fixed()