如何将作弊图绘制到屏幕并保存到文件

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

我正在使用 pheatmap 包。默认情况下,它将绘图绘制到屏幕上。就我而言,这意味着在 R studio 的 R markdown notebook 中输出。但我也想保存到文件中。如果我将它保存到一个文件中,并给它 filename= 参数,它不会绘制到屏幕上(R 笔记本)。有没有办法让这两件事都发生?更一般地说,对于我想要保存和显示在屏幕上的任何情节 (ggplot2)?

pheatmap 的作者似乎并没有让这变得超级简单。但这是您需要分两步完成的事情。首先,我们使用 ?pheatmap 帮助页面

中的样本数据
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 = "")

我们可以渲染图并用

保存结果
xx <- pheatmap(test)

然后您可以通过打开图形设备并按照在 main 函数中完成的方式重新绘制结果来将其输出到文件

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

这个包直​​接使用网格库而不使用 ggplot2 所以那个包的解决方案会有所不同。 ggsave 功能可以更轻松地将最后绘制的绘图保存到文件中。

仅供参考,我做了一个更复杂的函数,包括制作作弊图,然后从上面调用 save_heatmap 函数。如果它对任何人都有用,我会在这里发布它,也可以用于批评。我添加了一行来保存热图图像文件,其中包含产生热图的矩阵的名称。这有助于文件的下游组织。

save_pheatmap <- function(x, filename, width=480, height=960) {
   stopifnot(!missing(x))
   stopifnot(!missing(filename))
   png(filename,width = width, height=height)
   grid::grid.newpage()
   grid::grid.draw(x$gtable)
   dev.off()
}

plot_heatmap <- function(mat,color=NULL, cluster_rows=NULL, cluster_cols=NULL, scale=NULL, 
  cellwidth=NULL, cellheight=NULL,show_colnames=NULL, labels_col=NULL, show_rownames=NULL,
  border_color=NULL,legend=NULL,...){

  #Default Color
  if (is.null(color)){
    color=rev(col.pal)
  }

  #Default cluster
  if (is.null(cluster_rows)){
    cluster_rows=FALSE
  }

  if (is.null(cluster_cols)){
    cluster_cols=FALSE
  }

  #Default sclae
  if(is.null(scale)){
    scale="none"
  }

  #Default cell dims
  if (is.null(cellwidth)){
    cellwidth=12
  }

  if (is.null(cellheight)){
    cellheight=12
  }

  #Default Labels

  if (is.null(show_colnames)){
    show_colnames=TRUE
  }

  if (is.null(labels_col)){
    labels_col=NULL
  }

  if (is.null(show_rownames)){
    show_rownames=FALSE
  }

  #Set border

  if (is.null(border_color)){
    border_color=NA
  }

  #Legend

  if (is.null(legend)){
    legend=FALSE
  }


  temp_hm <- pheatmap(mat,color=color, cluster_rows=cluster_rows, cluster_cols=cluster_cols, scale=scale, 
  cellwidth=cellwidth, cellheight=cellheight,show_colnames=show_colnames, labels_col=labels_col,
  show_rownames=show_rownames,border_color=border_color,legend=legend)

  temp_hm_name <- paste(deparse(substitute(mat)),".png", sep="")

  save_pheatmap(temp_hm, filename=temp_hm_name)

}

MarkdownReports 中的 wplot_save_this() 函数将任何显示的绘图保存到 .pdf 文件中。此外,包中的所有其他绘图函数 (wbarplot (), whist(), wplot(), etc ) 分别自动显示和保存为 .pdf,并将它们链接到 Markdown 笔记本/报告。