Question

I'm not being able to add labels (sample size in this case) close to the boxplot when using fill aesthetics (or dodging the samples at x axis).

it works fine for the most used dataset (mtcars) and example

library(ggplot2)

fun_length <- function(x){
  return(data.frame(y=median(x),label= paste0("n=", length(x))))
}

ggplot(mtcars, aes(factor(cyl), mpg)) +
  geom_boxplot() +
  stat_summary(aes(x = factor(cyl)),
               fun.data = fun_length, geom = "text",
               vjust = +1, size = 4)

enter image description here

library(plyr)
ddply(mtcars, .(cyl), summarise, label = length(mpg))

  cyl label
1   4    11
2   6     7
3   8    14

But I can't add the same labels for this version, now showing sample sizes for each vs level.

ggplot(mtcars, aes(factor(cyl), mpg)) +
  geom_boxplot(aes(fill = factor(vs))) +
  stat_summary(aes(x=factor(cyl)),
               fun.data = fun_length, geom = "text")

ddply(mtcars, .(cyl, vs), summarise, label = length(mpg))

  cyl vs label
1   4  0     1
2   4  1    10
3   6  0     3
4   6  1     4
5   8  0    14

enter image description here

Any help will be welcome. Thanks in advance.

Was it helpful?

Solution

ggplot(mtcars, aes(factor(cyl), mpg)) +
  geom_boxplot(aes(fill = factor(vs)), position=position_dodge(.9)) +
  stat_summary(aes(x=factor(cyl), fill = factor(vs)), position=position_dodge(.9),
               fun.data = fun_length, geom = "text",
               vjust = +1, size = 4)

enter image description here

OTHER TIPS

This should work - move vs to the ggplot call and then you don't then need the aes in the stat_summary and add the position_dodge (for presentation)

ggplot(mtcars, aes(factor(cyl), mpg, fill = factor(vs))) +
  geom_boxplot(position=position_dodge(width=0.9)) +
  stat_summary( fun.data = fun_length, geom = "text", 
                      position=position_dodge(width=0.9), vjust=2)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top