heatmap.2 with color key on top

点点圈 提交于 2019-12-04 17:55:40

One can center the color key by adding "padding sections" ("5" and "6", in my particular case) to the lattice at the left (see the "#" comment over the last line of the code:

heatmap.2(x=matrix(rnorm(20*10), nrow=10), Rowv=NULL,Colv=NULL, 
          col = rev(rainbow(20*10, start = 0/6, end = 4/6)), 
          scale="none",
          margins=c(3,0), # ("margin.Y", "margin.X")
          trace='none', 
          symkey=FALSE, 
          symbreaks=FALSE, 
          dendrogram='none',
          density.info='histogram', 
          denscol="black",
          keysize=1, 
          #( "bottom.margin", "left.margin", "top.margin", "left.margin" )
          key.par=list(mar=c(3.5,0,3,0)),
          # lmat -- added 2 lattice sections (5 and 6) for padding
          lmat=rbind(c(5, 4, 2), c(6, 1, 3)), lhei=c(2.5, 5), lwid=c(1, 10, 1))

Not quite what you're asking for, but here's a way to create more or less the same plot using ggplot.

library(ggplot2)
library(reshape2)      # for melt(...)
library(grid)          # for unit(...)

set.seed(1)            # for reproducible example
df <- data.frame(matrix(rnorm(100*10), nr=10))
df.melt <- melt(cbind(x=1:nrow(df),df),id="x")
ggplot(df.melt,aes(x=factor(x),y=variable,fill=value)) +
  geom_tile() +
  labs(x="",y="")+
  scale_x_discrete(expand=c(0,0))+
  scale_fill_gradientn(name="", limits=c(-3,3),
                       colours=colorRampPalette(c('blue', 'yellow'))(12))+
  theme(legend.position="top", 
        legend.key.width=unit(.1,"npc"),legend.key.height=unit(.05,"npc"),
        axis.text=element_blank(),axis.ticks=element_blank())

I was able to solve my own problem with the colour key relative position, but fiddling around with the margin values associated with key.par

key.par=list(mar=c(bottom, left, top, right))

Just substitute in the values for 'bottom', 'left', 'top' and 'right' margins of the colour key that you want to adjust (the default margin for each is 4, which gives space for any labels).

key.par=list(mar=c(4,4,4,4)

uses the default margins.

key.par=list(mar=c(4,4,4,10))

would move it over from the right. You would have to see what value other than 10 works best for your plot.

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