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)

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.
The following solution is a slight modification of your code. All I did is change the data set by making new labels (PlantGrowth %>% group_by(group) %>% mutate(group2=paste(group,length(group))) %>%
ungroup()) and use the new labels as legends (fill=group2).
require(dplyr)
require(ggplot2)
bp <- ggplot(data=PlantGrowth %>% group_by(group) %>% mutate(group2=paste(group,length(group))) %>%
ungroup(), aes(x=group, y=weight, fill=group2)) + geom_violin() +
geom_dotplot(binaxis='y', stackdir='center', dotsize=0.5, binwidth = 0.01) +
stat_summary(fun.data = give.sample.size, geom = "text")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With