Search code examples
rmatrixcolorspheatmap

Define specific value colouring with pheatmap in R


Let's say:

m1<-matrix(rnorm(1000),ncol=100)

and defining colours:

cols = colorRampPalette(c("white", "red"))(30)

I am producing a heatmap without clustering with pheatmap function:

pheatmap(dist(t(m1)), cluster_rows = F, cluster_cols = F, show_rownames = TRUE, 
color = cols, main = 'Heatmap')

the question is, how can I define colours in order to get the same heatmap but only with pixels of specific value coloured (for example less than 0.1).

I tried to set

cols = ifelse(dist(t(m1))<0.1,'red','black')

but didn't work.


Solution

  • For a simple binary color scheme, you can use the breaks argument:

    library(pheatmap)
    
    set.seed(1)
    m1<-matrix(c(rnorm(1000)), ncol=100)
    
    pheatmap(dist(t(m1)),
             cluster_rows = F,
             cluster_cols = F,
             show_rownames = TRUE, 
             color = c("red", "black"),
             breaks = c(0, 3, 9),  # distances 0 to 3 are red, 3 to 9 black
             main = 'Heatmap')
    

    It looks like this:

    enter image description here

    If you prefer color gradients, it can be done as follows:

    m <- matrix(c(rnorm(1000)), ncol=100)
    distmat <- dist(t(m))
    
    # Returns a vector of 'num.colors.in.palette'+1 colors. The first 'cutoff.fraction'
    # fraction of the palette interpolates between colors[1] and colors[2], the remainder
    # between colors[3] and colors[4]. 'num.colors.in.palette' must be sufficiently large
    # to get smooth color gradients.
    makeColorRampPalette <- function(colors, cutoff.fraction, num.colors.in.palette)
    {
      stopifnot(length(colors) == 4)
      ramp1 <- colorRampPalette(colors[1:2])(num.colors.in.palette * cutoff.fraction)
      ramp2 <- colorRampPalette(colors[3:4])(num.colors.in.palette * (1 - cutoff.fraction))
      return(c(ramp1, ramp2))
    }
    
    cutoff.distance <- 3  
    cols <- makeColorRampPalette(c("white", "red",    # distances 0 to 3 colored from white to red
                                   "green", "black"), # distances 3 to max(distmat) colored from green to black
                                 cutoff.distance / max(distmat),
                                 100)
    
    pheatmap(distmat,
             cluster_rows = F,
             cluster_cols = F,
             show_rownames = TRUE, 
             color = cols,
             main = 'Heatmap')
    

    Which then looks like this:

    enter image description here