[R] 保存pheatmap图片对象到文件

一般我们使用pheatmap通过Rstudio交互得到的图片在plots的Export导出即可,如何保存对象到文件呢?这个需求在自动化流程中很常见,作者似乎也没说明。

生成示例数据:

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

看下数据亚子:
image.png

实现方法

接下来实现方法,分为两步:
1.保存对象

library(pheatmap)
xx <- pheatmap(test)

2. 打开图形设备重新画
这个包使用的是grid图形系统而非ggplot2,所以解决方法也是不同的。通过自定义函数来生成,也可一次绘制多个对象的图形。

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

image.png

Ref: https://stackoverflow.com/questions/43051525/how-to-draw-pheatmap-plot-to-screen-and-also-save-to-file

posted @ 2019-08-15 23:35  生物信息与育种  阅读(4794)  评论(0编辑  收藏  举报