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:
What I want:
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With