Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an expression in plot text - Printing the value of a variable rather than its name

Tags:

plot

r

I am trying to get a label to have an exponent in it. Here's 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 simply looks like this enter image description here

How do I get the actual vall to show up (and not the text "vall")

like image 398
CodeGuy Avatar asked Dec 28 '12 18:12

CodeGuy


1 Answers

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 doesn't work is that R never ends up evaluating vall:

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

plotmath tries to make something out of this but essentially vall is taken literally.

In general you don't need paste() in a plotmath expression, you can build the expression up using standard operators and through the use of layout operators. For example, for an expression equivalent to the one your example produced (unevaluated vall), all you really need is:

expression(R^2 == vall)

bquote() is one way to have an object replaced by its value in an expression. You wrap the object you want replaced by its value in .( ). R will then look for the object and takes its value and insert it into the expression.

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

like image 169
Gavin Simpson Avatar answered Oct 17 '22 08:10

Gavin Simpson