36
votes

Possible Duplicate:
Creating a facet_wrap plot with ggplot2 with different annotations in each plot
Add text to a faceted plot in ggplot2 with dates on X axis

Occasionally when faceting data in ggplot, I think it would be nice to annotate each facet with the number of observations that fell into each facet. This is particularly important when faceting may result in relatively few observations per facet.

What would be the best / simplest way to add an "n=X" to each facet of this plot?

require(ggplot2)
mms <- data.frame(deliciousness = rnorm(100),
                  type=sample(as.factor(c("peanut", "regular")), 100, replace=TRUE),
                  color=sample(as.factor(c("red", "green", "yellow", "brown")), 100, replace=TRUE))


plot <- ggplot(data=mms, aes(x=deliciousness)) + geom_density() + facet_grid(type ~ color)
1
up-voted for a including the image and reproducible data (cf. "creating a facet_wrap...") - flies

1 Answers

50
votes

It looks like this has been asked before, and I failed initially to see how they connected. I'm answering this here, but leaving it as not accepted in case someone has something more elegant. Also, the n = foo is a common enough case, that hopefully someone will get some use out of this question even though it's a bit duplicative.

require(ggplot2)
require(plyr)
mms <- data.frame(deliciousness = rnorm(100),
                  type=sample(as.factor(c("peanut", "regular")), 
                              100, replace=TRUE),
                  color=sample(as.factor(c("red", "green", "yellow", "brown")), 
                              100, replace=TRUE))


mms.cor <- ddply(.data=mms, 
                 .(type, color), 
                 summarize, 
                 n=paste("n =", length(deliciousness)))

plot <- ggplot(data=mms, aes(x=deliciousness)) + 
          geom_density() + 
          facet_grid(type ~ color) + 
          geom_text(data=mms.cor, aes(x=1.8, y=5, label=n), 
                    colour="black", inherit.aes=FALSE, parse=FALSE)

plot

The output