I'm not being able to add labels (sample size in this case) close to the boxplot when using fill aesthetics (or dodging the samples at x axis).
it works fine for the most used dataset (mtcars) and example
library(ggplot2)
fun_length <- function(x){
return(data.frame(y=median(x),label= paste0("n=", length(x))))
}
ggplot(mtcars, aes(factor(cyl), mpg)) +
geom_boxplot() +
stat_summary(aes(x = factor(cyl)),
fun.data = fun_length, geom = "text",
vjust = +1, size = 4)
library(plyr)
ddply(mtcars, .(cyl), summarise, label = length(mpg))
cyl label
1 4 11
2 6 7
3 8 14
But I can't add the same labels for this version, now showing sample sizes for each vs level.
ggplot(mtcars, aes(factor(cyl), mpg)) +
geom_boxplot(aes(fill = factor(vs))) +
stat_summary(aes(x=factor(cyl)),
fun.data = fun_length, geom = "text")
ddply(mtcars, .(cyl, vs), summarise, label = length(mpg))
cyl vs label
1 4 0 1
2 4 1 10
3 6 0 3
4 6 1 4
5 8 0 14
Any help will be welcome. Thanks in advance.