Skip to content
Prev 391286 / 398500 Next

[External] add equation and rsqared to plot

Yes, I also find it somewhat confusing. Perhaps this will help. I
apologize beforehand if I have misunderstood and you already know all
this.

The key is to realize that plotmath works with **expressions**,
unevaluated forms that include special plotmath keywords, like 'atop',
and symbols. So...

## simple example with plotmath used in plot's title

## This will produce an error, as 'atop' is not an R function:
plot(1,1, main = atop(x,y))

## to make this work, we need an expression on the rhs of 'main =' . A
simple way to do this is to use quote():

plot(1,1,main = quote(atop(x,y)))

## Note that this produce 'x' above 'y' **without quoting x and y**.
That's because
## this is an expression that plotmath parses and evaluates according
to its own rules,
## shown in ?plotmath

## Now suppose we have:
x <- 'first line'
y <- 'second line'

## and we want to display these quoted strings instead of 'x' and 'y'
in the title

## Then this will *not* work -- it gives the same result as before:
plot(1,1,main = quote(atop(x,y)))

## So what is needed here is R's 'computing on the language"
capability to substitute
## the quoted strings for x and y in the expression. Here are two
simple ways to do this:

## First using substitute()

plot(1,1, main = substitute(atop(x,y), list (x =x, y = y)))

## Second, using bquote()

plot(1,1, main = bquote(atop(.(x), .(y))))

## More complicated expressions can be built up using plotmath's rules.
## But you need to be careful about distinguishing plotmath expressions and
## ordinary R expressions. For example:

x <- pi/4  ## a number

## WRONG -- will display as written. bquote() is the same as quote() here.
plot(1,1, main = bquote(sin(pi/4) == round(x,2)))

## WRONG -- will substitute value of x rounded to session default
## in previous. This is a mistake in using bquote
plot(1,1, main = bquote(sin(pi/4) == round(.(x), 2)))

## RIGHT -- use of bquote
plot(1,1, main = bquote(sin(pi/4) == .(round(x,2))))
## or -- using substitute
plot(1,1, main = substitute(sin(pi/4) == x, list(x = round(x,2))))

Hope this is helpful and, again, apologies if I have misunderstood.

Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )
On Fri, Apr 8, 2022 at 7:42 AM PIKAL Petr <petr.pikal at precheza.cz> wrote: