It would probably make sense to let annotation_custom access facetting info *; this trivial change seems to do the trick,
library(ggplot2)
library(grid)
library(gridExtra)
annotation_custom2 <-
function (grob, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf, data)
{
layer(data = data, stat = StatIdentity, position = PositionIdentity,
geom = ggplot2:::GeomCustomAnn,
inherit.aes = TRUE, params = list(grob = grob,
xmin = xmin, xmax = xmax,
ymin = ymin, ymax = ymax))
}
p <- ggplot(mtcars) + geom_point(aes(mpg, wt)) + facet_wrap(~ cyl)
tg <- tableGrob(iris[1:2,1:2], rows=NULL)
# position the table within the annotation area
tg$vp=viewport(x=unit(0,"npc") + 0.5*sum(tg$widths),
y=unit(0,"npc") + 0.5*sum(tg$heights))
# need to wrap in a gTree since annotation_custom overwrites the vp
g <- grobTree(tg)
p + annotation_custom2(g, data=data.frame(cyl=8))
Edit * hadley has a different view though, annotation
is designed to appear in all panels. It’s not clear to me how to produce the geom equivalent for this particular case, if possible.