'R - Correlation heatmap created with ggplot2: How can I flip the labels on the y-axis?

I found this easy way to create a correlation heatmap using ggplot2:

data(attitude) 
library(ggplot2) 
library(reshape2) 
ggplot(melt(cor(attitude)), aes(Var1, Var2)) +   
     geom_tile(aes(fill = value))

However, this puts the variances on the antidiagonal of the matrix. I expected them on the diagonal. I tried to accomplish this using the rev() command:

ggplot(melt(cor(attitude)), aes(Var1, rev(Var2))) +
  geom_tile(aes(fill = value))

Which works fine as far as the colouring scheme inside the tiles is concerned. But the labels on the y-axis remain unchanged! What can I do about that? I'd rather not type in the correct order by hand, because my code should work for arbitrary data sets.



Solution 1:[1]

I've had this problem before, found an answer here: https://stackoverflow.com/a/14630937/4090947

Basicly:

data(attitude) 
library(ggplot2) 
library(reshape2) 

ggplot(melt(cor(attitude)), aes(Var1, ordered(Var2, levels =     rev(sort(unique(Var2)))))) +   
geom_tile(aes(fill = value))

This reverses your Y-axis

As your column names are discretes the key is to convert the strings (column names) to factors. Once you have factors, you can change the order.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community