Search code examples
rggplot2equationannotatesuperscript

How can I write an equation with superscripts using annotate in ggplot2?


I am having trouble figuring out how to write out an equation using annotate in ggplot2. Here is an example of what I want: I would like two lines on the graph, with N(t)=543.4172e^-0.00247259t, with the R^2 value below.

Here is an example of what I want to get, I just can't figure out how to get the superscripts in the equation and R^2 there.

Here is the code I have so far:

df4 <- data.frame(hours=c(0,1,3,5,12,24,48,96,168,336,504,720), copies=c(603.3,406,588,393.27,458.47,501.67,767.53,444.13,340.6,298.47,61.42,51.6))
p1 <- ggplot(df4, aes(x=hours, y=copies)) + geom_point() + stat_smooth(method = 'nls', method.args = list(start = c(a=543.4172,b=-0.00247)), formula = y~a*exp(b*x), se=FALSE, linetype=2, colour="pink") + theme_classic() + xlab("") + ylab("") + 
  annotate("text", x = 400, y = 750, label = "N(t)=543.4172e^-0.00247259t\nR^2 = 0.6933", color = "black", hjust = 0,  vjust = 1) +
  ggtitle(expression("eDNA pH 4"))
p1

I've been looking at other posts but just can't seem to get it to work.

Thanks in advance for any help or advice!


Solution

  • Another option would be to use parse=TRUE in annotate. Additionally your label requires some fixes to make it a valid expression. See ?plotmath.

    Note, TBMK you can't have any line breaks in math expressions. For that reason I added the two lines of your label via two annotates where I have set vjust so that they are plotted on top of each other:

    df4 <- data.frame(hours = c(0, 1, 3, 5, 12, 24, 48, 96, 168, 336, 504, 720), copies = c(603.3, 406, 588, 393.27, 458.47, 501.67, 767.53, 444.13, 340.6, 298.47, 61.42, 51.6))
    
    library(ggplot2)
    
    p1 <- ggplot(df4, aes(x = hours, y = copies)) +
      geom_point() +
      stat_smooth(
        method = "nls", method.args = list(start = c(a = 543.4172, b = -0.00247)), formula = y ~ a * exp(b * x),
        se = FALSE, linetype = 2, colour = "pink"
      ) +
      theme_classic() +
      xlab("") +
      ylab("") +
      annotate("text",
        x = 400, y = 750, label = "K(t) == 543.4172^{-0.00247259*t}",
        parse = TRUE,
        color = "black", hjust = 0, vjust = -.1
      ) +
      annotate("text",
        x = 400, y = 750, label = "R^2 == 0.6933",
        parse = TRUE,
        color = "black", hjust = 0, vjust = 1.1
      ) +
      ggtitle(expression("eDNA pH 4"))
    p1