Alright, this has got me stumped. I have this function:
tf <- function(formula = NULL, data = NULL) {
res <- as.character(formula[[2]])
fac2 <- as.character(formula[[3]][3])
fac1 <- as.character(formula[[3]][2])
# Aesthetic & Data 1
p <- ggplot(aes_string(x = fac1, y = res, color = fac1), data = data) +
facet_grid(paste(".~", fac2)) + geom_point() # OK if we only go this far
facCounts <- count(data, vars = c(fac2, fac1))
facCounts$label <- paste("n = ", facCounts$freq , sep = "")
facCounts$y <- min(data$res) - 0.1*diff(range(data$res))
facCounts <- facCounts[,-3]
names(facCounts) <- c("f2", "f1", "lab", "y") # data frame looks correct
# Aesthetic & Data 2
p <- p + geom_text(aes(x = f1, y = y, label = lab),
color = "black", size = 4.0, data = facCounts) + facet_grid(".~f2")
p
}
Which when run with this data and call:
set.seed(1234)
mydf <- data.frame(
resp = rnorm(40),
cat1 = sample(LETTERS[1:3], 40, replace = TRUE),
cat2 = sample(letters[1:2], 40, replace = TRUE))
p <- tf(formula = resp~cat1*cat2, data = mydf); print(p)
Produces this picture:

If you look carefully, you’ll see that the data in the two facets are actually the same. The counts are correct for that data that should be displayed (and is stored in facCounts). If the call to geom_text is commented out, then the plot is correct. A variety of changes to the geom_text call leave me with either what you see above, or the correct data is present but the count texts overlap. I can’t find the way out of this labyrinth! An attempt with + annotate("text", ...) doesn’t work either. What change is needed to keep the data faceted and the counts correct? Thanks. This is ggplot 0.9.3 btw.
Now that I’ve convinced myself that this will work:
You were calling
facet_grida second time using a differently named faceting variable. Removing the second call and renamingf2to `cat2 seems to work.