Problems adding `sample sizes` to ggplot violinplot legend

Viewed 778

I have the following ggplot2 violinplot

library(ggplot2)                                                                                                                                                                                                                                                                                                      
bp <- ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + 
             geom_violin() +
             geom_dotplot(binaxis='y', stackdir='center', dotsize=0.5, binwidth = 0.01)                      

enter image description here

It's unclear to me based on previous examples how to put labels in the legend (as seen with vplot(). I would like to put an integer just to the right of each label in the legend

ctrl 10
trt1 10
trt2 10

I've manually calculated these simply with

> table(PlantGrowth$group) 

What is the standard way to automatically do this? I've tried the function

give.sample.size <- function(x) {                                                                                                                                                                                                                                                                                                
    return(c(y = mean(x), label = length(x)))                                                                                                                                                                                                                                                                         
}                                                                                                                                                                                                                                                                                                                 


bp <- ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) +
   geom_violin() + 
   geom_dotplot(binaxis='y', stackdir='center', dotsize=0.5, binwidth = 0.01) + 
   stat_summary(fun.data = give.sample.size, geom = "text")

But this wouldn't affect the legend.

1 Answers
Related