如何使用 ggplot2 中的注释编写带有上标的方程式?

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

我无法弄清楚如何使用 ggplot2 中的注释写出方程。

这是我想要得到的例子,我只是不知道如何得到方程中的上标和那里的 R^2。

这是我目前的代码:

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

我一直在查看其他帖子,但似乎无法正常工作。

在此先感谢您的帮助或建议!

我认为 bquote 是 :

的答案
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 = bquote('N(t)=543.4172e'~e^(-0.00247259*t)),
    color = "black",
    hjust = 0,
    vjust = 1
  ) +
  annotate(
    "text",
    x = 400,
    y = 650,
    label = bquote(R^2~" = 0.6933"),
    color = "black",
    hjust = 0,
    vjust = 1
  ) +
  ggtitle(expression("eDNA pH 4"))
p1

另一种选择是在 annotate 中使用 parse=TRUE。此外,您的标签需要进行一些修复才能使其成为有效的表达式。参见 ?plotmath

请注意,TBMK 数学表达式中不能有任何换行符。出于这个原因,我通过两个 annotates 添加了你的标签的两行,我设置了 vjust 以便它们被绘制在彼此之上:

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