2

If I want to generate a multi-line expression I can do:

over = 'OVER'
below = 'BELOW'

x_lab_title = bquote(atop(.(over), .(below)))

ggplot(data.frame()) + xlab(x_lab_title)

However, I would like to make over and below expressions on their own, e.g.:

over = expression(X^2)
below = expression(Y^2)

but it does not work - renders a blank space instead (why is that?). In my scenario, the real expression is much more complicated, autogenerated, and changing between subsequent plots I generate, thus I cannot simply do:

x_lab_title = bquote(X^2, Y^2)

which would work in this particular case, but not for any other value of over and below.

krassowski
  • 13,598
  • 4
  • 60
  • 92

2 Answers2

3

The problem is that an expression() in R actually acts more like a container of expressions. What you really want is the language object inside the expression object. So you could either do

over = expression(X^2)
below = expression(Y^2)
x_lab_title = bquote(atop(.(over[[1]]), .(below[[1]])))

or, even better, skip the expression() and just use quote()

over = quote(X^2)
below = quote(Y^2)
x_lab_title = bquote(atop(.(over), .(below)))
MrFlick
  • 195,160
  • 17
  • 277
  • 295
0

After some hours of trial and error found a solution - this worked for me:

atop_string = paste0('bquote(atop(', toString(over), ',', toString(below), '))')
x_lab_title = eval(parse(text=atop_string))

This solution first assembles equivalent code representation and then parses it into an expression.

Even though I found a solution on my own, I am still curious why I cannot simply embed expressions in atop?

krassowski
  • 13,598
  • 4
  • 60
  • 92