I have a heatmap that continues to become more and more complex. An example of the melted data:
head(df2)
Class Subclass Family
Turning my comment into an answer with some simple demo data:
This isn't hard (there's even examples in ?facet_grid
, though they're towards the bottom).
# generate some nested data
dat = data.frame(x = rnorm(12), y = rnorm(12), class = rep(LETTERS[1:2], each = 6),
subclass = rep(letters[1:6], each = 2))
# plot it
ggplot(dat, aes(x, y)) + geom_point() +
facet_grid(subclass + class ~ .)
You can do this with arbitrarily many factors on either side of the ~
!
This will put a new strip to the right of the orignal strip, and to the left of the legend.
library(ggplot2)
library(gtable)
library(grid)
p <- ggplot(mtcars, aes(mpg, wt, colour = factor(vs))) + geom_point()
p <- p + facet_grid(cyl ~ gear)
# Convert the plot to a grob
gt <- ggplotGrob(p)
# Get the positions of the right strips in the layout: t = top, l = left, ...
strip <-c(subset(gt$layout, grepl("strip-r", gt$layout$name), select = t:r))
# New column to the right of current strip
gt <- gtable_add_cols(gt, gt$widths[max(strip$r)], max(strip$r))
# Add grob, the new strip, into new column
gt <- gtable_add_grob(gt,
list(rectGrob(gp = gpar(col = NA, fill = "grey85", size = .5)),
textGrob("Number of Cylinders", rot = -90, vjust = .27,
gp = gpar(cex = .75, fontface = "bold", col = "black"))),
t = min(strip$t), l = max(strip$r) + 1, b = max(strip$b), name = c("a", "b"))
# Add small gap between strips
gt <- gtable_add_cols(gt, unit(1/5, "line"), max(strip$r))
# Draw it
grid.newpage()
grid.draw(gt)