rggplot2pheatmap

How to draw pheatmap plot to screen and also save to file


I'm working with the pheatmap package. By default, it draws the plot to the screen. In my case, that means output in a R markdown notebook in R studio. But I also want to save to a file. If I save it to a file, giving it the filename= argument, it doesn't draw to the screen (R notebook). Is there a way to get both things to happen? And more generally, with any plot (ggplot2) where I want to both save and show on the screen?


Solution

  • The authors of pheatmap didn't seem to make this super easy. But it's something you are going to need to do in two separate steps. First, we use the sample data from the ?pheatmap help page

    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 = "")
    

    We can render the plot and save the result with

    xx <- pheatmap(test)
    

    Then you can output to this to a file by opening a graphics device and re-drawing the result the way it's done in the main function

    save_pheatmap_pdf <- function(x, filename, width=7, height=7) {
       stopifnot(!missing(x))
       stopifnot(!missing(filename))
       pdf(filename, width=width, height=height)
       grid::grid.newpage()
       grid::grid.draw(x$gtable)
       dev.off()
    }
    save_pheatmap_pdf(xx, "test.pdf")
    

    This package uses the grid library directly and does not use ggplot2 so solutions for that package would be different. The ggsave function makes it easier to save the last drawn plot to a file.