R - 使用ggplot2创建的相关热图:如何在y轴上翻转标签?

时间:2015-04-02 17:59:22

标签: r ggplot2 heatmap correlation

我发现使用ggplot2创建相关热图的这种简单方法:

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

现在我经常看到的相关矩阵在主对角线上有差异,而不是在反对角线上。

我尝试使用rev()命令完成此操作:

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

就瓷砖内部的着色方案而言,其工作正常。但是y轴上的标签保持不变!我该怎么办? 我不想手工输入正确的顺序,因为我的实际代码应该适用于任意数据集。

1 个答案:

答案 0 :(得分:2)

我以前遇到过这个问题,在这里找到答案: 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))

这会反转你的Y轴

由于您的列名是离散的,因此关键是将字符串(列名称)转换为因子。一旦有了因素,就可以改变顺序。