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

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


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=""))> eq2expression(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.