使用带对象的多线表达式注释ggplot图?

时间:2018-06-03 23:38:29

标签: r ggplot2 expression plotmath

我想在我的ggplot上添加两行,上标和上标以及对象的引用。

我发现annotate()函数调用geom_text()parse = TRUE可以使用plotmath中的表达式。

如果这是我的标签:

q10 = 1.9
a = 3.9
b = -0.05

lab1 = substitute(atop(paste(Q[10], '=', q10), paste(M[O[2]], '=', a, e^(b*T))), list(q10 = q10 = 1.9, a = 3.9, b = -0.05))

然后它将与基础图一起使用:

plot(1, 1, main = lab1)

enter image description here

但是当我尝试将它与ggplot()一起使用时,它会抛出一个错误:

ggplot(diamonds, aes(carat, price, color = cut)) + 
  geom_point() +
  annotate(geom = 'text', x = 4, y = 5000, label = lab1, parse = TRUE, color = 'blue')

Error: Aesthetics must be either length 1 or the same as the data (1): label, colour

我在ggplot中找到了与多行注释相关的问题:R ggplot annotated with atop using three values and bgoup

与ggplot中的表达式相关:ggplot2 annotation with superscripts

但我无法弄清楚如何结合适当的答案来制作工作注释。有ggplot2大师的帮助吗?

1 个答案:

答案 0 :(得分:2)

要将plotmath与ggplot一起使用,请将其作为字符串传递 - parse = TRUE指的是解析字符串。因此:

library(ggplot2)

ggplot(diamonds, aes(carat, price, color = cut)) + 
    geom_point() +
    annotate(geom = 'text', x = 4, y = 5000, 
             label = "atop(Q[10] == 1.9,M[O[2]] == 3.9*e^(-0.05*T))", 
             parse = TRUE, color = 'blue')

如果您需要替换字符串,请使用pasteglue::glue

相关问题