Flip/transpose a heatmap in ggplot2

早过忘川 提交于 2019-12-01 21:06:18

问题


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


回答1:


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

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

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

EDIT: Apologies about the weird image format/layout.



来源:https://stackoverflow.com/questions/36624374/flip-transpose-a-heatmap-in-ggplot2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!