Search code examples
rggplot2plottidyverseexpression

Plotting fractions using `bquote(frac( .(number), .(number)) )` in ggplot2


I'm trying to plot fractions inside a geom_tex(label = ) using the bquote(frac( .(number), .(number)) ) syntax.

But it seems ggplot2 doesn't recognize this. Is there a way to plot these fractions correctly?

Reproducible data and code plus what I tried:

set.seed(0)
DATA <- data.frame(
  x=sample(0:1,50,T),
  y=sample(LETTERS[1:2],50,T))

library(ggplot2)

ggplot(DATA)+aes(x=x,y=after_stat(count)/ sapply(PANEL, \(x) sum(count[PANEL == x])))+
  geom_bar() +
  
# Problem starts with `label =`:
  geom_text(aes(y = after_stat(count)/ sapply(PANEL, \(x) sum(count[PANEL==x])),
            label = bquote(frac(.(after_stat(count)), .(sapply(PANEL, \(x) sum(count[PANEL==x])))))),
            vjust = -.1, color = "black", size = 2, stat = "count") +
  
  facet_grid(vars(y))

Solution

  • One option would be to create your plotmath expression as a character string and use parse=TRUE in geom_text:

    library(ggplot2)
    #> Warning: package 'ggplot2' was built under R version 4.3.1
    
    ggplot(DATA) +
      aes(x = x, y = after_stat(count) / sapply(PANEL, \(x) sum(count[PANEL == x]))) +
      geom_bar() +
      geom_text(
        aes(
          y = after_stat(count) / sapply(PANEL, \(x) sum(count[PANEL == x])),
          label = after_stat(
            paste0(
              "frac(", count, ", ",
              sapply(PANEL, \(x) sum(count[PANEL == x])), ")"
            )
          )
        ),
        vjust = -.1, color = "black", size = 2, stat = "count", 
        parse = TRUE
      ) +
      facet_grid(vars(y))