Annotate x-axis with N in faceted plot
<p>I'm trying to produce a boxplot of some numeric outcome broken down by treatment condition and visit number, with the number of observations in each box placed under the plot, and the visit numbers labeled as well. Here's some fake data that will serve to illustrate, and I give two examples of things I've tried that didn't quite work.</p>

<pre><code>library(ggplot2)
library(plyr)

trt      &lt;- factor(rep(LETTERS[1:2],150),ordered=TRUE)
vis      &lt;- factor(c(rep(1,150),rep(2,100),rep(3,50)),ordered=TRUE)
val      &lt;- rnorm(300)
data     &lt;- data.frame(trt,vis,val)
data.sum &lt;- ddply(data, .(vis, trt), summarise,
            N=length(na.omit(val)))
mytheme  &lt;- theme_bw() + theme(panel.margin = unit(0, "lines"), strip.background = element_blank())
</code></pre>

<p>The below code produces a plot that has N labels where I want them. It does this by grabbing summary data from an auxiliary dataset I created. However, I couldn't figure out how to also label visit on the x-axis (ideally, below the individual box labels), or to delineate visits visually in other ways (e.g. lines separating them into panels).</p>

<pre><code>plot1    &lt;- ggplot(data) + 
            geom_boxplot(aes(x=vis:trt,y=val,group=vis:trt,colour=trt), show.legend=FALSE) +
            scale_x_discrete(labels=paste(data.sum$trt,data.sum$N,sep="\n")) +
            labs(x="Visit") + mytheme
</code></pre>

<p>The plot below is closer to what I want than the one above, in that it has a nice hierarchy of treatments and visits, and a pretty format delineating the visits. However, for each panel it grabs the Ns from the first row in the summary data that matches the treatment condition, because it doesn't "know" that each facet needs to use the row corresponding to that visit.</p>

<pre><code>plot2    &lt;- ggplot(data) +     geom_boxplot(aes(x=trt,y=val,group=trt,colour=trt), show.legend=FALSE) +
            facet_wrap(~ vis, drop=FALSE, switch="x", nrow=1) +
            scale_x_discrete(labels=paste(data.sum$trt,data.sum$N,sep="\n")) +
            labs(x="Visit") + mytheme
</code></pre>