I wrote this function a while back to label the facet with the standard deviation, mean or count.
#' Function will update the name with the statistic of your choice
AddNameStat <- function(df, category, count_col, stat = c("sd","mean","count"), dp= 0){
# Create temporary data frame for analysis
temp <- data.frame(ref = df[[category]], comp = df[[count_col]])
# Aggregate the variables and calculate statistics
agg_stats <- plyr::ddply(temp, "ref", summarize,
sd = sd(comp),
mean = mean(comp),
count = length(comp))
# Dictionary used to replace stat name with correct symbol for plot
labelName <- plyr::mapvalues(stat,
from=c("sd","mean","count"),
to=c("\u03C3", "x", "n"))
# Updates the name based on the selected variable
agg_stats$join <- paste0(agg_stats$ref, ": ", labelName," = ",
round(agg_stats[[stat]], dp))
# Map the names
name_map <- setNames(agg_stats$join, as.factor(agg_stats$ref))
return(name_map[as.character(df[[category]])])
}
# Create a label for the facet
mtcars$label <- AddNameStat(mtcars, "carb", "cyl", stat = "count")
mtcars %>%
ggplot(aes(x = cyl)) + geom_bar()+
facet_wrap(~label)