I am trying to write an equation like "R^2=0.00575" in the legend, and the number 0.00575 can be embedded in the legend automatically. Here is an example.
set.seed(100)
x=rnorm(100)
y=1:100
fit=lm(y~x)
R_squared=format(summary(fit)$r.squared,digits = 3)
plot(x,y,type="l")
legend("topleft",legend =expression(R^{2}~"="~R_squared),bty = "n")
As the figure shows, the variable "R_squared"
is not embedded in the equation. Is there any solution? Thanks.
For this task I think it is best to do parse(text=sprintf(...))
. You can code the R language syntax into the string literal to be parsed into an R expression using parse()
, and use sprintf()
format specifications to embed any numeric or string values that are stored in variables into the expression.
set.seed(100L);
x <- rnorm(100L);
y <- 1:100;
fit <- lm(y~x);
R_squared <- format(summary(fit)$r.squared,digits=3L);
plot(x,y,type='l');
legend('topleft',legend=parse(text=sprintf('paste(R^2,\' = %s\')',R_squared)),bty='n');
An alternative syntax that leverages the fact that ==
is plotted as a single equal sign:
legend('topleft',legend=parse(text=sprintf('R^2 == %s',R_squared)),bty='n');
See the plotmath documentation.
You can also use bquote
:
set.seed(100L);
x <- rnorm(100L);
y <- 1:100;
fit <- lm(y~x);
R_squared <- format(summary(fit)$r.squared,digits=3L);
plot(x,y,type='l');
legend('topleft',legend=bquote(R^{2} ~ "=" ~ .(R_squared)),bty='n');
More information on partial substitution of expressions with bquote
can be found here, which defines the function as:
An analogue of the LISP backquote macro. bquote quotes its argument except that terms wrapped in .() are evaluated in the specified where environment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With