0

I can add the number of observations in a boxplot like this: Add number of observations per group in ggplot2 boxplot

Is it possible to add the relative frequencies? On the example above, I would add 0.66, 0.33, 0.5 and 0.5 texts instead of 12, 6, 7, 7.

So far I've managed to compute the absolute frequency of the top factor:

library(ggplot2)

give.n <- function(x){
  return(c(y = median(x)*1.05, label = length(x))) 
  # experiment with the multiplier to find the perfect position
}

ggplot(mtcars, aes(factor(vs), mpg, colour = factor(am))) + 
    geom_boxplot() +
    stat_summary(fun.data = give.n, geom = "text", fun.y = median) + 
    stat_summary(aes(factor(vs), mpg, colour = factor(am)), inherit.aes = F, fun.data = give.n, geom = "text", fun.y = median)

Thanks

brucekane
  • 11
  • 1
  • 3
  • https://stackoverflow.com/questions/43414864/ggplot2-boxplot-stat-summary-text-placement-by-group – Tung Sep 12 '18 at 02:13
  • This won't do the job because it does not allow for calculating the relative freq. The stat_summary function only gets the vector for the specific boxplot bar, it won't get the values of the other 2 bars that compose x=1, for example. So the function can count the observations but can't calculate the relative freq. On the example I gave I can get n=(12,6,7,7) with the first stat_summary) and n=(18,14) with the second. Can I funnel the result of one stat_summary into another, or maybe store the values in a variable then use them on the second stat_summary call, is it possible? – brucekane Sep 12 '18 at 20:43

0 Answers0