How to include Grouped Parenthesis in ggplot geom_text?

mathexpression <- expression(
  paste(
    "log",
    bgroup("(",     #1open
           paste(
             "log",
              bgroup("(",         #2open
                    bgroup("(",frac(1,2)%*%     #3open
                             bgroup("(",1+exp(-beta),")"), #4openclose
                           ")")^-frac(1,beta),      #3close
                    ")")^-frac(1,gamma)  #3close
           ),")")#1close and paste close
  )#paste
)#expression
plot(0,0)
mtext(side=1, mathexpression)

Looking to have this expression in a ggplot geom text. I understand that geom_text does not take an expression but a string. I need help constructing this string containing a bgroup so ggplot can parse it.

I'm more used to using bquote than expression for writing equations, so this solution uses that. As mathexpression creates a long string deparse wants to line break so width.cutoff needs to be set.

  library(ggplot2)
  mathexpression <- bquote(
    log~bgroup("(",
      log~bgroup("(",
        bgroup("(", 
          frac(1, 2)%*%bgroup("(",
            1+exp(-beta),                 
          ")"),
        ")")^-frac(1,beta), 
      ")")^-frac(1,gamma), 
    ")")
  )

  df <- data.frame(x = c(-1 , 1), y = c(-1, 1))
  ggplot(df, aes(x, y)) + 
    annotate(
      "text", 
      x = 0,
      y = 0, 
      label = deparse(mathexpression, width.cutoff = 160), 
      parse = TRUE
    )

3 Likes

Thank you very much this is exactly what I needed.