Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining paste() and expression() functions in plot labels

Tags:

plot

r

Consider this simple example:

labNames <- c('xLab','yLabl') plot(c(1:10),xlab=expression(paste(labName[1], x^2)),ylab=expression(paste(labName[2], y^2))) 

What I want is for the character entry defined by the variable 'labName, 'xLab' or 'yLab' to appear next to the X^2 or y^2 defined by the expression(). As it is, the actual text 'labName' with a subscript is joined to the superscripted expression.

Any thoughts?

like image 747
aaron Avatar asked Feb 11 '11 20:02

aaron


1 Answers

An alternative solution to that of @Aaron is the bquote() function. We need to supply a valid R expression, in this case LABEL ~ x^2 for example, where LABEL is the string you want to assign from the vector labNames. bquote evaluates R code within the expression wrapped in .( ) and subsitutes the result into the expression.

Here is an example:

labNames <- c('xLab','yLab') xlab <- bquote(.(labNames[1]) ~ x^2) ylab <- bquote(.(labNames[2]) ~ y^2) plot(c(1:10), xlab = xlab, ylab = ylab) 

(Note the ~ just adds a bit of spacing, if you don't want the space, replace it with * and the two parts of the expression will be juxtaposed.)

like image 190
Gavin Simpson Avatar answered Sep 17 '22 15:09

Gavin Simpson