如何用图例中的变量编写方程?

Yan*_*ang 4 plot equation r 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")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

如图所示,变量"R_squared"未嵌入方程中。有什么解决办法吗?谢谢。

bgo*_*dst 5

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

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');
Run Code Online (Sandbox Code Playgroud)

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

legend('topleft',legend=parse(text=sprintf('R^2 == %s',R_squared)),bty='n');
Run Code Online (Sandbox Code Playgroud)

请参阅plotmath 文档

阴谋