How to implement after_stat(ymax) with count expression in r?

36 views Asked by At

I would like to add n numbers to each ggplot box plots with the italic(n) = #.

I have tried expression and bquote for label but did not work. Any suggestion?

stat_summary(fun = median, fun.max = length,geom = "text", aes(label = expression(paste(~italic(n)," = ", after_stat(ymax) )) ), vjust = -5)

on title,

ggtitle(bquote(paste("POLAR - HR | ", ~italic(n), " = ", .(sum(df.summ$file.len)) )))

works well.

1

There are 1 answers

1
stefan On

Not sure whether there is an option to make expression work with after_stat. But one option would be to create your label as a character string and use parse=TRUE in geom_text.

Minimal reprex based on mtcars:

library(ggplot2)

ggplot(mtcars, aes(factor(cyl), mpg)) +
  stat_summary(
    fun = median, fun.max = length,
    geom = "text",
    aes(
      label = after_stat(paste0("italic(n) == ", ymax))
    ), vjust = .5, parse = TRUE
  )