Search code examples
rheatmappheatmap

Change pheatmap plot background colour


Is there a way I can change the plot background of pheatmap plot in R from white to let say black

library(pheatmap)
# Create test matrix
test = matrix(rnorm(200), 20, 10)
test[1:10, seq(1, 10, 2)] = test[1:10, seq(1, 10, 2)] + 3
test[11:20, seq(2, 10, 2)] = test[11:20, seq(2, 10, 2)] + 2
test[15:20, seq(2, 10, 2)] = test[15:20, seq(2, 10, 2)] + 4
colnames(test) = paste("Test", 1:10, sep = "")
rownames(test) = paste("Gene", 1:20, sep = "")
# Draw heatmapspheatmap(test)
pheatmap(test)

I tried, but it was not succesful

 pheatmap(test , bg="black")

Or is there a way to combine pheatmap with ggplot2 function of theme(plot.background = element_rect(colour = 'black', fill = 'black'))


Solution

  • You can change the colors of grobs in the object generate by pheatmap:

    p <- pheatmap(test)
    
    library(grid)
    # Set white color for dendrogram lines and for text
    for (k in c(1,2,4,5)) {
      p$gtable$grobs[[k]]$gp <- gpar(col="white")
    }
    p$gtable$grobs[[6]]$children[[2]]$gp <- gpar(col="white", fontsize=10)
    # Draw a black box behind the heatmap as background
    grid.draw(rectGrob(gp=gpar(fill="black", lwd=0)))
    # Draw the heatmap
    grid.draw(p)
    

    enter image description here

    Edit. As suggested by @Keniajin, a shorter solution is:

    grid.draw(rectGrob(gp=gpar(fill="black", lwd=0)))
    grid.draw(p)
    grid.gedit("layout", gp = gpar(col = "white", text = ""))