Search code examples
rplottext-formatting

R - Text Formatting of Plot Text that is not hard-wired


I would like to add formatted text to a plot (title, axes labels, legend, etc.). A standard solution would be e.g.

plot(1, 1, ylab=substitute(lambda[1]))

where the y-axis label will be the greek letter λ with subscript 1. That is what I want but unfortunatelly it is hard-wired. I would like it to be flexible, i.e. to have an option to pass the text as an argument of a function. So, looking at r help, I found that the argument for substitute is an expression. So I've tried

sometext <- "lambda[1]"
e <- parse(text="sometext")
plot(1, 1, ylab=substitute(e))

But substitute ignores that e is an object an simply prints the text 'e' as the label. So instead I tried

plot(1, 1, ylab=eval(e))

which was better because eval at least evaluates the expression but the label now is literally 'lambda[1]', i.e. it is not evaluated as a greek letter λ with a subscript. I then explicitly stated that 'e' is an expression doing

e <- expression(sometext)

and running the two previous plot commands but with the same results as before. The closest I came to what I wanted ot achieve was doing

plot(1, 1, ylab=substitute(var[i], list(var="lambda", i=1)))

where at least the 1 is printed as a subscript but the text 'lambda' instead of the greek letter λ is printed.

Any suggestions on how can I achieve what the first command does but not hard-wired? E.g. using a string and somehow converting it to the right object so that it will be displayed properly? Thanks.

Daniel


Solution

  • You can pass the label as an expression like so and then use substitute inside the function:

    dwat <- function(expr){
    
    plot(1, 1, ylab = substitute(expr))
    
    }
    
    dwat(lambda[1])
    dwat(mu[2])
    

    If you want to pass a string instead of an expression use parse:

    dwat_string <- function(string){
    
    plot(1, 1, ylab = parse(text = string))
    
    }
    
    dwat_string("mu[1]")
    

    Another option would be to use the ellipsis approach. That way you can pass an xlab or any other argument to plot:

    dwat2 <- function(...){
    
    plot(1, 1, ...)
    
    }
    
    dwat2(ylab = expression(lambda[1]))