Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw boxes around "groups" in a heatmap?

I made a graph like this:

library(reshape2)
library(ggplot2)

m <- matrix(1:64 - 32, 8)
rownames(m) <- colnames(m) <-
  c(paste0("a", 1:3), paste0("b", 1:2), paste0("c", 1:3))
d <- melt(m)
gg <- ggplot(d) +
  geom_tile(aes(x = Var1, y = Var2, fill = value)) +
  scale_fill_gradient2()

How can I programmatically draw boxes around the "a", "b", and "c" groups?

The matrix m will always be square. colnames(m) and rownames(m) will always be the same. Therefore the boxes will be cover the entire grid and will never overlap. The group sizes will vary, in general.

I'm also not married to ggplot2. I'm open to a solution in base graphics with image if it's not fussier than the ggplot2/grid version.

I got as far as

d$group <- substr(d$Var1, 1, 1)

before I realized I had no clue how to proceed.


What I have:

enter image description here

What I want:

enter image description here

like image 737
shadowtalker Avatar asked Dec 15 '22 14:12

shadowtalker


1 Answers

Or geom_segment

library('reshape2')
library('ggplot2')

m <- matrix(1:64 - 32, 8)
rownames(m) <- colnames(m) <-
  c(paste0("a", 1:3), paste0("b", 1:2), paste0("c", 1:3))
gg <- ggplot(melt(m)) +
  geom_tile(aes(x = Var1, y = Var2, fill = value)) +
  scale_fill_gradient2()

tt <- table(gsub('\\d+', '', colnames(m)))
ll <- unname(c(0, cumsum(tt)) + .5)

gg + geom_segment(aes(x = ll, xend = ll, y = head(ll, 1), yend = tail(ll, 1))) + 
  geom_segment(aes(y = ll, yend = ll, x = head(ll, 1), xend = tail(ll, 1)))

enter image description here

like image 178
rawr Avatar answered Jan 07 '23 23:01

rawr