Search code examples
rheatmapcontinuousspectrumgplots

Generating a Heatmap From Data Range in R


I have generated a list (named "trans") of dataframes in R. Each list has 3 columns: slope, start, and stop. Here is a small portion of the data:

> trans
$a
          slope       start       stop
1  0.0006718865 -0.85576923 -1.0000000
2 -0.0005769719 -0.65384615 -0.8557692
3  0.0000698207 -0.50000000 -0.6538462
4 -0.0001124370 -0.26923077 -0.5000000
5  0.0005659248 -0.03846154 -0.2692308

$b    
          slope       start       stop
1  5.689229e-04 -0.85148515 -1.0000000
2 -1.613771e-04 -0.23762376 -0.8514851
3  9.879804e-05 -0.03960396 -0.2376238

In each row, "slope" is the value of interest, whereas "start" and "stop" indicate the range for which this slope exists. The "start" and "stop" values for all dataframes span from roughly -0.04 to -1. My dataframes have different numbers of rows.

I would like to plot, preferably as a heatmap, the different slopes throughout the range of -0.04:-1, such that each row of the heatmap represents each dataframe from my list. Is there an elegant way to do this with the current set of information that I've generated? The only solution I can think of would be to transform each data frame into 2 columns, where every value within each start-stop range (to 10^10 decimal place!)is listed in one column, with the slope in that range listed in the other column.

I am very familiar with heatmap.2 from the gplots package, but have to wonder if a plot like this is something I will have to make from scratch.


Solution

  • I am guessing what you are aiming for, but I think you can achieve this with ggplot2::geom_rect().

    a <- read.table(textConnection("
    slope       start       stop
    1  0.0006718865 -0.85576923 -1.0000000
    2 -0.0005769719 -0.65384615 -0.8557692
    3  0.0000698207 -0.50000000 -0.6538462
    4 -0.0001124370 -0.26923077 -0.5000000
    5  0.0005659248 -0.03846154 -0.2692308
    "))
    
    b <- read.table(textConnection("
    slope       start       stop
    1  5.689229e-04 -0.85148515 -1.0000000
    2 -1.613771e-04 -0.23762376 -0.8514851
    3  9.879804e-05 -0.03960396 -0.2376238"))
    
    
    trans <- list(a = a,b = b)
    
    trans2 <- do.call(rbind, lapply(seq_along(trans),function(x) cbind(trans[[x]],name = x)))
    
    
    require(ggplot2)
    
    ggplot(trans2, aes(xmin = name, xmax = (name+1),
                       ymin = start, ymax = stop,
                       fill = slope)) +
      geom_rect() +
      scale_x_continuous(breaks = seq_along(trans)+.5, labels = names(trans))
    

    Result:

    plot