Heatmap.2 with a color key on top

I have the following code to show the color key above the heatmap. But the color key is not accurate on top (slightly shifted to the right) of the heatmap. Does anyone know how to make sure that the color does not move? In addition, how to remove the empty space to the right of the heat map? Thanks.

library(gplots)
heatmap.2(
  matrix(rnorm(100*10), nrow=100)
  , dendrogram='none'
  , Colv = F
  , Rowv = F
  , trace='none'
  , col = colorRampPalette(c('blue', 'yellow'))(12)
  , labRow=NA
  , labCol=NA
  , density.info='none'
  , lmat=rbind(c(4, 2), c(1, 3)), lhei=c(2, 8), lwid=c(4, 1)
)

heatmap.2 example

+2
source share
3 answers

You can center the color key by adding “indentation” (in my case, “5” and “6”) to the grid on the left (see comment “#” on the last line of 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))

centered legend of heatmap. 2 ()

+6
source

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

+1

I was able to solve my problem with the relative position of the color key, but was messing around with the field values ​​associated with key.par

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

Just replace the values ​​for the “lower”, “left”, “upper” and “right” fields of the color key that you want to configure (the default for each is 4, which gives space for any labels).

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

uses default fields.

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

will move it to the right. You will need to see which value other than 10 is best for your plot.

0
source

Source: https://habr.com/ru/post/1620218/


All Articles