2

I've made a heatmap in R using heatmap.2 and the only thing I can't figure out is how to control the presence and labeling of tick marks on the color key. I have an example below. What I would like to do is have tick marks at the beginning and end of the color key to indicate the range of values (in this case 0-1), rather than 6 tick marks with labels at 0, 0.4 and 0.8. I'm sure there is a simple way to control this but I can't seem to find it.

library('gplots')

data <- c(0, 0.1, 0.1, 0.2, 0.2, 0.7, 0.7, 0.8, 1)
matr <- matrix(data, 3, 3)

heatmap.2(matr, trace="none", density.info="none")

enter image description here

EDIT:

The only fix I can find is to directly change heatmap.2 itself to accept additional arguments as this seems to be hardcoded (in my case I want to add a min and max range for the color key).

Original heatmap.2

heatmap.2 <-function (...)
{
...
lv <- pretty(breaks)  # line 362
...
}

Changed to:

heatmap.2 <-function (..., xMin = NULL, xMax = NULL, ...)
{
...
if(is.null(xMin)) lv <- pretty(breaks)
else lv <- c(xMin, xMax)
...
}
James
  • 1,100
  • 1
  • 13
  • 29
  • You might not be able to post an image, but you can surely post a [Great reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – MattLBeck May 12 '14 at 16:12
  • It seems the actual ticks that get labeled are different from one user/computer to the next. When I run the above code I get labels, as I mention, at 0, 0.2, 0.6 and 1, whereas when Henrik did it, he got labels at 0, 0.4 and 0.8. Maybe relevant but I'm using R V3.0.3 and gplots 2.12.1. – James May 12 '14 at 18:58

1 Answers1

4

The "key.xtickfun" argument is what you want. Pass a function to this argument that returns a named list whose elements will be passed to the "axis" function.

In the function, I get "breaks" from the parent frame (the gplots environment), make them pretty, and keep only the first and last break, which are the min and max. Then, return a list with "at" and "labels". "at" is the values returned from the scale01 function (also from the parent frame) called on the breaks. "labels" are the labels, which should be the breaks themselves.

heatmap.2(matr, trace="none", density.info="none",
          key.xtickfun = function() {
            breaks = pretty(parent.frame()$breaks)
            breaks = breaks[c(1,length(breaks))]
            list(at = parent.frame()$scale01(breaks),
                 labels = breaks)
          })
Ben Ernest
  • 445
  • 3
  • 14