Search code examples
rcombinationsheatmappheatmap

Combining pheatmaps in R


I've been working around with no success in solving how 2 or more pheatmaps (heatmaps) can be combined in a final plot.

data1 <- structure(list(DC1 = c(NA, NA, 1.98), DC2 = c(NA, NA, 0.14), 
    DC3 = c(1.85, 1.51, 0.52), DC4 = c(0.89, 0.7, 1.47), DC5 = c(0, 
    0.78, 0), DC6 = c(0, 1.3, 0), DC7 = c(0, 1.47, 0), DC8 = c(0, 
    1.2, 0), DC9 = c(0, 0, 0), DC10 = c(0.51, 1.9, 0)), .Names = c("DC1", 
    "DC2", "DC3", "DC4", "DC5", "DC6", "DC7", "DC8", "DC9", "DC10"), 
    enter code here`class = "data.frame", row.names = c("A", "B",  "C"))

data 2 <- structure(list(DC1 = c(9.56, 1.87, 2.07, 1.87, 2.07, 1.35), DC2 = c(5.51, 1.13, 1.25, 1.13, 0.99, 0.45), DC3 = c(4.84, 1.17, 0.66, 1.17, 
0.34, 0.16), DC4 = c(4.18, 0.59, 0.05, 0.97, 0.43, 0.59), DC5 = c(3.26, 
0, 0.14, 0.31, 0.79, 0.63), DC6 = c(3.35, 0, 1.12, 0.05, 1.12, 
0), DC7 = c(4.18, 0.63, 1.27, 0.47, 1.27, 0), DC8 = c(4.37, 1.17, 
1.3, 1.17, 0, 0), DC9 = c(4.3, 1.13, 0, 1.13, 0, 0), DC10 = c(7.47, 
1.88, 0.71, 1.88, 0, 0)), .Names = c("DC1", "DC2", "DC3", "DC4", 
"DC5", "DC6", "DC7", "DC8", "DC9", "DC10"), class = "data.frame", row.names = c("TD6 vs SH", 
"TD6 vs SAP", "TD6 vs NEA", "SH vs SAP", "SH vs NEA", "SAP vs NEA"
))

I construct very easily a heatmap using pheatmap by using these two codes:

hm_data1 <- pheatmap(as.matrix(data1))
hm_data2 <- pheatmap(as.matrix(data2))

However, in no way I can get both printed in one figure. I would like to see both of them horizontally. However, my real figure will be composed by 16 pheatmaps, so they must be arrange in 4 columns and 4 rows.

I tried with par mfrow with no success.

How can I combine pheatmaps?

I know there are plenty of R packages that can plot heatmaps, but I would like to do it with pheatmap


Solution

  • This will work.

    library(gridExtra); library(pheatmap)
    
    m <- matrix(c(1:4), ncol=2)
    n <- matrix(c(1,1,1,2), ncol=2)
    a <- list(pheatmap(m)[[4]])
    a[[2]] <- pheatmap(n)[[4]]
    z <- do.call(grid.arrange,a)
    plot(z)
    

    Based on one of the comments. If you have many single plots; you can use a loop like this.

    mn <- list(m, n)
    
    a <- list()
    for(i in 1:length(mn)){
      a[i] <- list(pheatmap(mn[[i]])[[4]])
    }
    
    z <- do.call(grid.arrange,a)
    plot(z)
    

    The point is it to add all the data for your single plots in a list. You can then loop over the list, applying pheatmap.