Using an expression in the text of the plot - printing the value of a variable, not its name

I am trying to get a label with an indicator in it. Here is the code I have

vall = format(cor(x,y)*cor(x,y),digits=3) eq <- expression(paste(R^2," = ",vall,sep="")) text(legend.x,legend.y,eq,cex=1,font=2) 

But the text just looks like this enter image description here

How to get the actual vall to display (and not the text "vall")

+7
source share
1 answer

Try bquote() , for example:

 set.seed(1) vall <- format(rnorm(1),digits=3) eq <- bquote(bold(R^2 == .(vall))) sq <- seq(0, 1, by = 0.1) plot(sq, sq, type = "n") text(0.5, 0.5, eq) 

The reason your example does not work is because R never completes the vall evaluation:

 > eq2 <- expression(paste(R^2," = ",vall,sep="")) > eq2 expression(paste(R^2, " = ", vall, sep = "")) 

plotmath tries to make one of this, but essentially vall is taken literally.

In the general case, you do not need paste() in the plotmath expression, you can build the expression using standard operators and using layout operators. For example, for an expression equivalent to the expression obtained by your example (unevaluated vall ), all you really need is:

 expression(R^2 == vall) 

bquote() is one way to replace an object with its value in an expression. You wrap the object you want to replace with its value in .( ) . R will search for the object and take its value and insert it into the expression.

See also substitute() for an alternative approach to this with a different interface.

+14
source

All Articles