2

Is there any way to use the glue package to write plotmath expressions? See an example below where I would like to use glue::glue to prepare an annotation for a plot.

Or, actually, any other compact way to display the labels containing results would be helpful for me.

# 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]]))
)
)

Created on 2018-02-25 by the reprex package (v0.2.0).

Indrajeet Patil
  • 4,673
  • 2
  • 20
  • 51

1 Answers1

1

Instead of using substitute, a compact option would be 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))

enter image description here

akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Thanks! That's what I was looking for: a compact way to write the results for a label. Just went straight to `glue::glue`, but your option also works for me. – Indrajeet Patil Feb 25 '18 at 16:38