Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an equation with a variable in legend?

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")

enter image description here

As the figure shows, the variable "R_squared" is not embedded in the equation. Is there any solution? Thanks.

like image 821
Yang Yang Avatar asked Jan 06 '23 15:01

Yang Yang


2 Answers

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.

plot

like image 143
bgoldst Avatar answered Jan 14 '23 17:01

bgoldst


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.

like image 29
desc Avatar answered Jan 14 '23 18:01

desc