2

I would like to make an heatmap in R using pheatmap with the colors green, black and red and using a range in the legend from -2 to 2, here is the code that I used:

library(pheatmap)
my_palette <- colorRampPalette(c("green", "black", "red"))(n = 201)
colors = c(seq(as.numeric(-2),-0.01,length=100), 0, 
seq(0.01,as.numeric(2),length=100))

pheatmap(mFilt_annot_sort_matrix, color = my_palette, breaks = colors, scale = 
"none", cluster_rows = F, cluster_cols = F, margin = c(5,5))

The problem is that I would like the values less than -2 in green an greater than 2 in red while with my solution these values are white, could you help me?

M--
  • 25,431
  • 8
  • 61
  • 93
user40267
  • 51
  • 2
  • 5
  • If you provide a sample dataset using `dput(df)` I can plot the graph for that. Look at [How to make a great reproducible example in R?](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – M-- Jun 07 '17 at 13:35
  • In case somebody ran into this question with slightly different needs, you can refer to this question: [Pheatmap Color for Specific Value](https://stackoverflow.com/questions/41783245/pheatmap-color-for-specific-value). – M-- Jun 12 '17 at 18:40

1 Answers1

2

You need to set the break-point to be at -2 and +2 and make a gradient in between. You also need to set the color for less than minimum and greater than maximum desired values. Look below;

library(pheatmap)

colors <- c(min(mFilt_annot_sort_matrix),seq(-2,2,by=0.01),max(mFilt_annot_sort_matrix))

my_palette <- c("green",colorRampPalette(colors = c("green", "black", "red"))
                                                   (n = length(colors)-3), "red")


pheatmap(mFilt_annot_sort_matrix, color = my_palette, breaks = colors, scale = 
"none", cluster_rows = F, cluster_cols = F, margin = c(5,5))

Example using a normal data;

Using rnorm.within function I make the following data-set:

#V1 is random between -4 and 4 
#V2 is less than -2
#V3 is greater than 2

df <- data.frame(cbind(rnorm.within(1000, -4, 4)
,rnorm.within(1000,-4,-3), rnorm.within(1000,3,4))) 

and applying the procedure above (same breaks and color pallet) for making a heatmap will get:

pheatmap(df, color = my_palette, breaks = colors, scale = 
                  "none", cluster_rows = F, cluster_cols = F, margin = c(5,5))

   

M--
  • 25,431
  • 8
  • 61
  • 93