I want to add annotations such as n=5, n=4 with the number of data points in each boxplot at the top edge of my geom_boxplot plot.
I am aware I can do this with geom_text by precomputing the counts,
but it seems that ggplot2, having all these wonderful binning and summarizing
functionality, ought to be able to do this itself?
Let's assume we have these data:
library(tidyverse)
dd = tribble(
~val, ~kind,
1, 'A',
3, 'A',
5, 'A',
5, 'A',
6, 'A',
3, 'B',
4, 'B',
4, 'B',
5, 'B'
)
I have tried this:
> base = ggplot(dd, aes(x=kind, y=val)) + geom_boxplot()
> base + geom_text(y=6, label=..count.., stat='count')
Error in layer(data = data, mapping = mapping, stat = stat, geom = GeomText, :
object '..count..' not found
Presumably, geom_text has simply ignored my stat parameter?
Next, I tried this:
> base + stat_count(aes(y=6, label=..count..), geom='text')
Error: stat_count() must not be used with a y aesthetic.
Shouldn't it be my own problem whether I can do anything useful with
the resulting ..count.., "y aesthetic" or not?
Both of these attempts appear sensible to me.
Can anybody explain conceptually why ggplot2 does not accept these commands?
And whether there is any approach with ggplot2-supplied counting that will work?

stat_countexample if you don't inherit theyaesthetic. The text will be plotted at the count value. You can move those viaposition_nudgeory = ..count.. - somevaluebut, of course, that means the labels end up not being lined up if there are different counts per group.stat_count( aes(x = kind, label = paste0("n = ", ..count..) ), geom = "text", position = position_nudge(y = -2), inherit.aes = FALSE )