<p>I am thankful for <a href='http://www.biostars.org/p/18211/'>Obi Griffith sharing his code on how to make heatmaps</a> in R where you can add row and column information together with the color mapping information. I use it all the time to make pictures of hierarchically clustered expression profiles measured by expression arrays. </p>

<p>Usually I scale the input matrix on rows (probesets) to Z-scores in order to make weigh equally in the clustering. The colors of the heatmap are mapped linearly to the Z-scores. \</p>

<p>The problem is, when you have a few extremes in your data set, they tend to make your heatmap a little faint. In the attached heatmap you can see that the Z-scores range from somewhere around -10 to 10, however, about 99% is in the range of -4 to 4. I would like to change the way colors are mapped to the Z-scores in such a way that the green-to-red goes from -4 to 4 and the colors of the Z-scores outside this range just do not become any more green or red then they are already, any ideas?</p>

<pre><code># import gplots for greenred colors
library(gplots)
# generate random matrix
x&lt;-replicate(100,rnorm(100,0,1))
# draw heatmap
heatmap.3(x,density.info="histogram",col=greenred)
# introduce outliers
x[1,1] &lt;- -10
x[2,2] &lt;- 10
# draw heatmap with outliers
heatmap.3(x,density.info="histogram",col=greenred)
</code></pre>

<p><img src='http://s24.postimg.org/pakmr8sv9/heatmap_without_Extremes.png%20without_extremes' alt='Without extremes' />
<img src='http://s10.postimg.org/6npznmu3d/heatmap_with_Extremes.png%20with_extremes' alt='With extremes' /></p>

<p>You can use the <code>breaks</code> argument to do this, from the <code>heatmap.2</code> documentation:</p>

<blockquote>breaks    
(optional) Either a numeric vector indicating the splitting points for binning x into colors, or a integer number of break points to be used, in which case the break points will be spaced equally between min(x) and max(x)</blockquote>

<p>To use to achieve your desired effect:</p>

<pre><code>#breaks for the core of the distribution
breaks=seq(-4, 4, by=0.2) #41 values
#now add outliers
breaks=append(breaks, 10)
breaks=append(breaks, -10, 0)
#create colour panel with length(breaks)-1 colours
mycol &lt;- colorpanel(n=length(breaks)-1,low="green",mid="black",high="red")
#now plot heatmap - I'm using heatmap.2, but am assuming this will work with Obi's heatmap.3
heatmap.2(x,density.info="histogram",col=mycol, trace='none', breaks=breaks)
</code></pre>

<p>The major drawback is that the outliers are a lot less obvious, but clearly the heatmap overall is a lot less 'washed out'.</p>

<p>Results:</p>

<p>Before
<img src='http://bioinf1.ncl.ac.uk/biostar/heatmap_before.png' alt='enter image description here' /></p>

<p>After
<img src='http://bioinf1.ncl.ac.uk/biostar/heatmap_after.png' alt='enter image description here' /></p>
