如何在热图图上添加黑线

bil*_*999 2 charts plot r line ggplot2

我创建以下样本热图:

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")
Run Code Online (Sandbox Code Playgroud)

这将产生如下图: 在此处输入图片说明

我的问题是如何添加暗线以分隔选定的图块?我已使用第三方软件程序在下图中说明了这一点:

在此处输入图片说明

MrF*_*ick 5

您可以定义一组新点来描述您要绘制的线段。我们使用以下事实:每个图块都位于整数网格的中心,并且宽度为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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明