使用 glue::glue 编写 plotmath 表达式,如斜体字体或希腊字母

using glue::glue to write plotmath expressions like italic fontface or greek letters

有什么方法可以使用glue包来写plotmath表达式吗?请参阅下面的示例,其中我想使用 glue::glue 为绘图准备注释。

或者,实际上,任何其他显示包含结果的标签的紧凑方式对我都有帮助。

# libraries needed
library(broom)
library(stats)
library(datasets)
library(cowplot)
library(ggplot2)

# getting results from a linear regression model
res <-
  broom::tidy(x = stats::lm(data = iris,
                            formula = Sepal.Length ~ Species))

# display the results
print(res)
#>                term estimate  std.error statistic       p.value
#> 1       (Intercept)    5.006 0.07280222 68.761639 1.134286e-113
#> 2 Speciesversicolor    0.930 0.10295789  9.032819  8.770194e-16
#> 3  Speciesvirginica    1.582 0.10295789 15.365506  2.214821e-32

# preparing a subtitle with results for "versicolor" species
glue::glue("The estimate for {res$term[2]} is {expression(italic(beta))} = {res$statistic[2]}") # italic or beta doesn't work here
#> The estimate for Speciesversicolor is italic(beta) = 9.03281939401064

# usually one would do something like
cowplot::ggdraw(cowplot::add_sub(
  plot = ggplot(data.frame()) + geom_point() + xlim(0, 10) + ylim(0, 100), # create empty plot
  label = substitute(expr = 
    paste(
      "The estimate for ",
      effect,
      " is ",
      italic(beta),
      " = ",
      estimate,
      sep = " "
    )
  , env = base::list(effect = res$term[[2]], estimate = res$statistic[[2]]))
)
)

reprex package (v0.2.0) 创建于 2018-02-25。

而不是使用 substitute,一个紧凑的选项是 bquote

lbl <- bquote("The estimate for"~.(res$term[2])~is ~italic(beta) == .(res$statistic[2]))

cowplot::ggdraw(cowplot::add_sub(
 plot = ggplot(data.frame()) + 
                 geom_point() +
                 xlim(0, 10) +
                  ylim(0, 100), 
        label =  lbl))