Following this question: Add number of observations per group in ggplot2 boxplot, how do I change the colours of stat_summary?
Below is the example code:
give.n <- function(x){
return(c(y = median(x)*1.05, label = length(x)))
}
p <- ggplot(mtcars, aes(factor(vs), mpg, colour = factor(am))) +
geom_boxplot() +
stat_summary(fun.data = give.n, geom = "text", fun.y = median,
position = position_dodge(width = 0.75))
p
So when I do the below to change the colours, it doesn't work (it gives me only 1 combined number)
stat_summary(fun.data = give.n, geom = "text", fun.y = median,
position = position_dodge(width = 0.75), colour = c("black", "red"))
And when I do the below to add the text "n=" it doesn't work either. (I try to add the "n=" in the function itself, by doing the below:
give.n <- function(x){
return(c(y = median(x)*1.05, label = paste0("n=",length(x))))
}
But I get the below error:
Error: Discrete value supplied to continuous scale