在ggplot2中翻转/转置热图

6
下面的代码生成从左下角到右上角的热图。
library(ggplot2)
library(reshape2)
set.seed(111)

n <- 10
m <- matrix(rnorm(n^2), n, n)
m <- cor(m)
m <- melt(m)

ggplot(m, aes(Var1, Var2, fill = value)) + 
    geom_tile()

enter image description here

如何修改我的数据(可能是修改熔解结果),以便热图从左上角到右下角,就像这样的结果 enter image description here

7
... aes(rev(Var1), Var2, fill = value) ...?还是 + scale_x_reverse() - Axeman
2个回答

3
与@Axeman的解决方案相比,这个解决方案很糟糕(但更有趣),它是将旋转变换矩阵应用于数据。为了理解我们需要什么样的变换,我在三维散点图上仅绘制了对角线(值=1)点。
旋转矩阵公式是围绕z轴(值)旋转
加上常数后,最终方程式为
可能有更好的向量化转换方法,但这就是我所做的。
rot_m <- matrix(c(0,-1,0,1,0,0,0,0,1),3,3)

ftransform <- function(x){
   t(rot_m %*% as.numeric(matrix(m[x,],3,1)) + matrix(c(0,11,0),3,1))
 }

foo <- lapply(1:nrow(m),ftransform)

foo <- data.frame(do.call(rbind,foo))
names(foo) <- c("Var1","Var2","value")
ggplot(foo, aes(Var1,Var2,fill=value)) + 
   geom_tile()

编辑:对于奇怪的图像格式/布局表示歉意。

这段内容与IT技术无关,只是一些说明。

不错。但是你的脚本中没有定义m。 - ben
m已在问题中定义。 - Adam Birenbaum

1

这对我起作用

ggplot(m, aes(aes(reorder(Var1, desc(Var1)), Var2, fill = value)) + 
    geom_tile()

结果图


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接