heatmaps: controlling the color representation with set data range

Often you want to set the fixed colors for particular range of your dataset to be sure that the visual output is correctly represented. This is particularly useful for time series data, where the range or your dataset might drastically change during the course of the simulation.

To do that in R, we need to set the “breaks” parameter in plotting functions such as image or heatmap.2.

# gplots contains the heatmap.2 function

# create 50x10 matrix of random values from [-1, +1]
random.matrix  <- matrix(runif(500, min = -1, max = 1), nrow = 50)

# following code limits the lowest and highest color to 5%, and 95% of your range, respectively
quantile.range <- quantile(random.matrix, probs = seq(0, 1, 0.01))
palette.breaks <- seq(quantile.range["5%"], quantile.range["95%"], 0.1)

# use http://colorbrewer2.org/ to find optimal divergent color palette (or set own)
color.palette  <- colorRampPalette(c("#FC8D59", "#FFFFBF", "#91CF60"))(length(palette.breaks) - 1)



    dendrogram = "row",
    scale      = "none",
    trace      = "none",
    key        = FALSE,
    labRow     = NA,
    labCol     = NA,

    col    = color.palette,
    breaks = palette.breaks

Enjoy plotting! mintgene


7 thoughts on “heatmaps: controlling the color representation with set data range

  1. Would there be a way to add a gradient colorbar with corresponding numerical values as a key?

  2. Usually I plot the gradient bar separate from the data plot. There might be more elegant way to get around this, but with the usage of image editing the outcome is very similar.

    Here’s the code I use:

    palette.breaks <- seq(-1, 1, 0.001)
    color.palette  <- colorRampPalette(c("#FC8D59", "#FFFFBF", "#91CF60"))(length(palette.breaks) - 1)
    plot(NULL, xlim = c(-1, 1), ylim = c(0, 1), bty = "n", yaxt = "none", ylab = "", xlab = "")
    segments(palette.breaks[-length(palette.breaks)], rep(0, length(palette.breaks) - 1), palette.breaks[-length(palette.breaks)], rep(1, length(palette.breaks) - 1), lwd = 2, col = color.palette)
  3. Hey just wanted to give you a brief heads up and let you know a few of the
    images aren’t loading properly. I’m not sure why but I think its a linking issue.
    I’ve tried it in two different browsers and both show the same

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s