Search code examples
rplotmath

using expressions (plotmath) on axis in r


This works fine

data = c(1,3,2)
max_y <- max(data)
plot_colors <- c("blue")
plot(data, type="l", col=plot_colors[1], ylim=c(0,max_y), axes=FALSE, xlab=expression(e[3]))
axis(1, at=c(1,2,3),  lab=expression(e[1],e[2],e[3])  )

But I would like to read the labels on the x-axis from a file. I tried the following:

data = c(1,3,2)
names = vector("expression",3)
names[1] = "e[1]"
names[2] = "e[2]"
names[3] = "e[3]"
max_y <- max(data)
plot_colors <- c("blue")
plot(data, type="l", col=plot_colors[1], ylim=c(0,max_y), axes=FALSE, xlab=expression(e[3]))
axis(1, at=c(1,2,3),  lab=names  )

I tried substitute:

axis(1, at=c(1,2,3),  lab=substitute(expression(a), list(a="e[1],e[2],e[3]"))  )

but this also did not work. Any suggestion?


Solution

  • What you want is ?parse:

    names = c('e[1]', 'e[2]', 'e[3]')
    namesExp = do.call(c, lapply(names, function(x) parse(text = x)))
    plot(c(1,3,2), type='l', col='blue', axes=FALSE, xlab = expression(e[3]))
    axis(3, at=c(1,2,3), lab = names)
    axis(1, at=c(1,2,3), lab = namesExp)
    

    Above, lapply returns a list of expressions:

    > print(lapply(names, function(x) parse(text = x)))
    [[1]]
    expression(e[1])
    [[2]]
    expression(e[2])
    [[3]]
    expression(e[3])
    

    The do.call just non-recusrively unlists it (also can use unlist(lapply(names, function(x) parse(text = x)), recursive = F)):

    > print(do.call(c, lapply(names, function(x) parse(text = x))))
    expression(e[1], e[2], e[3])