在ggplot2中翻转/转置热图 [英] Flip/transpose a heatmap in ggplot2

查看:486
本文介绍了在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

推荐答案

与@Axeman相比,一个可怕的解决方案(但更有趣)是将旋转变换矩阵应用于数据.

A terrible solution compared to @Axeman's (but more fun) is to apply a rotational transformation matrix to the data.

要了解我们需要哪种转换,我只在3D散点图上绘制了对角线(值= 1).

To understand what kind of transformation we need, I plotted only the diagonal (value=1) points on a 3D scatter plot.

围绕z(值)轴的旋转矩阵

The rotational matrix about the z (value) axis

包括添加的常量在内,最终方程为

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

对怪异的图像格式/布局表示歉意.

Apologies about the weird image format/layout.

这篇关于在ggplot2中翻转/转置热图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆