Вы можете построить «бар» отдельно и комментировать свою фигуру.
Например,
library(ggplot2)
library(reshape2)
groups <- data.frame(samp_id = factor(1:100), group = c(rep('A', 20), rep('B', 50), rep('C', 30)))
dat <- matrix(rnorm(500), nrow = 100)
# make group B distinguishable
dat[groups$group=='B',] <- dat[groups$group=='B',] + 4
hm <- ggplot(melt(dat), aes(fill = value, x = Var2, y = Var1)) + geom_tile() + theme_classic() +
theme(axis.title.y = element_blank(),
axis.text.x = element_blank())
# Build a legend "bar"
leg <- ggplot(groups, aes(y = samp_id, x = 0)) + geom_point(aes(color = group), shape = 15, size = 3, show.legend = F) +
theme_classic() +
theme(axis.title = element_blank(), axis.line = element_blank(),
axis.text = element_blank(), axis.ticks = element_blank(),
plot.margin = unit(c(0,0,0,0), "cm"))
leg
# annotate hm with the bar
hm + annotation_custom(ggplotGrob(leg),
xmin = .2, xmax = .5,
ymin = 0, ymax = 100.5) # n + .5 since tiles are 1 in width centered on the value
выводит следующие значения: