如何在图例中写一个带有变量的方程式?

How to write an equation with a variable in legend?

我正在尝试在图例中写一个类似 "R^2=0.00575" 的等式,数字 0.00575 可以自动嵌入到图例中。这是一个例子。

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

如图所示,变量"R_squared"没有嵌入到等式中。有什么解决办法吗?谢谢

对于这个任务我认为最好做parse(text=sprintf(...))。您可以使用 parse(), and use sprintf() 格式规范将 R 语言语法编码为要解析为 R 表达式的字符串文字,以将存储在变量中的任何数字或字符串值嵌入到表达式中。

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');

利用 == 被绘制为单个等号这一事实的替代语法:

legend('topleft',legend=parse(text=sprintf('R^2 == %s',R_squared)),bty='n');

参见plotmath documentation

您也可以使用 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');

有关使用 bquote 部分替换表达式的更多信息,请参见 here,它将函数定义为:

An analogue of the LISP backquote macro. bquote quotes its argument except that terms wrapped in .() are evaluated in the specified where environment.