Charité Learner
Charité Learner

Reputation: 394

How to use pheatmap in R to draw a box outside a pheatmap plot and save them together

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)

I want to produce a heatmap by pheatmap in R and add a box alongside the heatmap margin.

I tried several methods just like the above script but failed.

The key point is that I also want to save it through ggsave after the box produced.

Hope somebody give some help on this question.

Thanks in advance.

Upvotes: 1

Views: 114

Answers (1)

Marco Sandri
Marco Sandri

Reputation: 24272

The solution proposed below is based on the use of grobs (graphical objects) from the grid package. It is not an elegant solution, but it works.

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

Upvotes: 1

Related Questions