Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using expressions (plotmath) on axis in r

Tags:

r

plotmath

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?

like image 921
dziadgba Avatar asked Mar 16 '26 00:03

dziadgba


1 Answers

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])
like image 185
lockedoff Avatar answered Mar 18 '26 13:03

lockedoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!