【问题标题】:Annotate ggplot plot with a multiline expression with objects?用带有对象的多行表达式注释 ggplot 图?
【发布时间】:2018-11-13 06:41:11
【问题描述】:

我想在我的 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)

但是当我尝试将它与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 大师有什么帮助吗?

【问题讨论】:

    标签: r ggplot2 expression plotmath


    【解决方案1】:

    要将 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

    【讨论】:

    • 谢谢@alistaire。对于其他人:最终的解决方案是:lab1 = paste0('atop(Q[10] ==', q10, ', M[O[2]] ==', a, '*e^(', b, '*T))')
    猜你喜欢
    • 2021-02-20
    • 2018-05-13
    • 2012-01-27
    • 1970-01-01
    • 2010-10-13
    • 2011-01-28
    • 2016-07-20
    • 2019-12-25
    相关资源
    最近更新 更多