Search code examples
rplotmath

Merging expressions for plotting


I'm trying to merge two expressions made with bquote. For example:

a = 1
b = 2

x1 = as.expression(bquote(paste("Something ", alpha, " = ", .(a), sep = "")))
x2 = as.expression(bquote(paste("Something else ", beta, " = ", .(b), sep = "")))

Is there a way to do something similar to x12 = paste(x1, x2, collapse = "some symbol") without doing:

x12 = as.expression(bquote(paste("Something ", alpha, " = ", .(a)," some symbol ",
"Something else ", beta, " = ", .(b), sep = "")))

Thanks a lot!


Solution

  • You can write a small function that combines plotmath expressions:

    a = 1
    b = 2
    
    x1 = bquote("Something " * alpha == .(a))
    x2 = bquote("Something else " * beta == .(b))
    
    comb_plotmath <- function(...) {
      Reduce(function(x, y) substitute(x * y, env = list(x = x, y = y)), 
             list(...))
    }
    
    
    plot.new()
    text(0.5, 0.5, comb_plotmath(x1, " some symbol ", x2))
    

    Results in:

    resulting plot displaying the expression

    Note that paste in plotmath has no sep parameter. You might want to study help("plotmath").