如何在热图上添加暗线

How to add dark lines to heat map plot

我创建了以下示例热图:

library(reshape2) 
library(ggplot2) 
require(gridExtra)
library(RColorBrewer)
colors <- brewer.pal(9, 'Reds')
sample_data <- data.frame(matrix(sample(36, 36), nrow=6))
sample_data$id<-rownames(sample_data)
sample_data2 <- melt(sample_data, id.var="id")
ggplot(sample_data2, aes(as.factor(variable), as.factor(id), group=id)) +
    geom_tile(aes(fill = value)) + 
    geom_text(aes(fill = sample_data2$value, label = sample_data2$value), size=3) +
    scale_fill_gradientn(colours = colors) + 
    labs(x = "variable", y = "id", title="heat map")

这会生成如下图:

我的问题是如何添加暗线来分隔选定的图块?我使用了第三方软件程序来说明以下情节中的想法:

您可以定义一组新的点来描述您要绘制的线段。我们利用每个图块都以整数网格为中心并且宽度为 1 的事实。

my.lines<-data.frame(x=c(.5,4.5), y=c(5.5,.5), 
    xend=c(4.5,4.5), yend=c(5.5,5.5))

ggplot(sample_data2, aes(as.factor(variable), as.factor(id), group=id)) +
    geom_tile(aes(fill = value)) + 
    geom_text(aes(fill = sample_data2$value, label = sample_data2$value), size=3) +
    scale_fill_gradientn(colours = colors) + 
    labs(x = "variable", y = "id", title="heat map") + 
    geom_segment(data=my.lines, aes(x,y,xend=xend, yend=yend), size=3, inherit.aes=F)