简体   繁体   English

在 ggplot2 中翻转/转置热图

[英]Flip/transpose a heatmap in ggplot2

Code bellow generates heatmap that goes from bottom left to top right下面的代码生成从左下角到右上角的热图

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()

在此处输入图像描述

How can I modify my data (probably modify melt result) so heatmap would go from top left to bottom right, for result like this我如何修改我的数据(可能修改熔化结果)以便热图从左上角到右下角为 go,结果如下在此处输入图像描述

A terrible solution compared to @Axeman's (but more fun) is to apply a rotational transformation matrix to the data.与@Axeman 的(但更有趣)相比,一个糟糕的解决方案是对数据应用旋转变换矩阵。

To understand what kind of transformation we need, I plotted only the diagonal (value=1) points on a 3D scatter plot.为了理解我们需要什么样的变换,我只在 3D 散点图上绘制了对角线(值=1)点。

The rotational matrix about the z (value) axis绕 z(值)轴的旋转矩阵

Including the added constant, the final equation is包括添加的常数,最终方程为

There is probably a better way to vectorize this transformation, but this is how I did it.可能有更好的方法来矢量化这种转换,但我就是这样做的。

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()

EDIT: Apologies about the weird image format/layout.编辑:对奇怪的图像格式/布局表示歉意。

This works for me这对我有用

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

result plot结果 plot

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM