如何在R中使用pheatmap在pheatmap图外绘制一个框并将它们保存在一起

问题描述 投票:0回答:1
library(pheatmap)
p<-pheatmap(matrix(rnorm(100,0,1),10,10),
         cluster_rows = F,
         cluster_cols = F,
         cellwidth = 20,
         cellheight = 15)
p
plot(NULL, axes = FALSE, xlab = "", ylab = "", xlim = c(0, 2.5), ylim = c(0, 1))
rect(xleft = 0.635, xright = 1.6, ybottom = 0.18, ytop = 0.775)
p
rect(xleft = 0.635, xright = 1.6, ybottom = 0.18, ytop = 0.775)

ggsave(p,filename = paste0("test","_",format(Sys.Date(), format = "%m_%d"),".pdf"),width =6,height = 6,dpi = 1200)

我想通过 R 中的 pheatmap 生成热图,并在热图边距旁边添加一个框。

我尝试了多种方法,就像上面的脚本,但失败了。

关键是我还想在盒子产生后通过ggsave保存

希望有人对这个问题给予一些帮助。

提前致谢。

r rect pheatmap
1个回答
0
投票

下面提出的解决方案基于使用

grid
包中的 grobs(图形对象)。这不是一个优雅的解决方案,但它确实有效。

library(pheatmap)
library(grid)

set.seed(1234)
p <- pheatmap(matrix(rnorm(100,0,1),10,10),
         cluster_rows = F,
         cluster_cols = F,
         cellwidth = 20,
         cellheight = 15)

rect1 <- p$gtable$grobs[[1]]$children[[1]]

rect2 <- grid::rectGrob(x = unit(0,"npc"), y=unit(0,"npc"),  
                        width = unit(1, "npc"), height = unit(1, "npc"), 
                        just=c("left", "bottom"), 
                        gp=gpar(color="black", fill="transparent", lex=2))

p$gtable$grobs[[1]] <- gTree(children=gList(rect1, rect2))

print(p)

ggsave(p, filename = paste0("test","_",format(Sys.Date(), format = "%m_%d"),".pdf"),
       width=6, height=6, dpi=1200)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.