繁体   English   中英

如何在两个图上用r2值写出线的方程

[英]How to write equation of line with r2 value on two plots

我想比较两个线性回归图并在图上或稍微上方打印它们各自的eqns。 我不知道如何使方程式与r2值一起出现并放在它们各自的图上(理想情况下在一条线上)。 文本文件简单如下:

num abs
0.875   0.128
1.75    0.262
2.5 0.579 
5   1.292 
10  2.151 
.875    0.185
1.75    0.273
2.5 0.507 
5   1.561 
10  2.581

谢谢您的帮助。

d <- read.table("C:/Users/trinh/OneDrive/Documents/R scripts/BSA.txt", header=T)
attach(d)
da <- d[1:5,]
da2 <- d[6:10,]
reg.da <- lm(abs[1:5]~ num[1:5])
reg.da2 <- lm(abs[6:10]~num[6:10])
par(mfrow=c(1,2))

#1st plot
plot(da,main="Regression line for BSA-1",xlab="[BSA]",ylab="Abs")
abline(reg.da)

#second plot
plot(da2,main="Regression line for BSA-2",xlab="[BSA]",ylab="Abs")
abline(reg.da2)

#establish b intercept/slope and r^2
cf<-round(coef(reg.da2),2)
r2.1<-format(summary(reg.da2)$r.squared, digits = 3)

#first eqn:
eq1<-paste("y = ",cf[1],
    ifelse(sign(cf[2])==1, " + ", " - "), cf[2],"x")
mtext(eq1,side=3)
mtext(bquote(r^2 == .(r2.1)),adj=1)

#establish b intercept/slope and r^2
cf1<-round(coef(reg.da),2)
r2.2<-format(summary(reg.da)$r.squared, digits = 3)

#second eqn:
eq2<-paste("y =", cf1[1],
    ifelse(sign(cf1[2])==1, " + ", " - "), cf1[2],"x")
mtext(eq2,side=3)
mtext(bquote(r^2 == .(r2.2)),adj=1)

在添加第二个图之前,应放置第一个图的文本。 以下代码用于根据您的数据生成示例图。 我将cex=0.7添加到mtext()的参数中以减小文本的大小并避免方程干扰r平方值。

par(mfrow=c(1,2))

#1st plot
plot(da,main="Regression line for BSA-1",xlab="[BSA]",ylab="Abs")
abline(reg.da)
#establish b intercept/slope and r^2
cf<-round(coef(reg.da2),2)
r2.1<-format(summary(reg.da2)$r.squared, digits = 3)

#first eqn:
eq1<-paste("y = ",cf[1],
           ifelse(sign(cf[2])==1, " + ", " - "), cf[2],"x")
mtext(eq1,side=3,adj=0,cex=0.7)
mtext(bquote(r^2 == .(r2.1)),adj=1,cex=0.7)

#second plot
plot(da2,main="Regression line for BSA-2",xlab="[BSA]",ylab="Abs")
abline(reg.da2)

#establish b intercept/slope and r^2
cf1<-round(coef(reg.da),2)
r2.2<-format(summary(reg.da)$r.squared, digits = 3)

#second eqn:
eq2<-paste("y =", cf1[1],
           ifelse(sign(cf1[2])==1, " + ", " - "), cf1[2],"x")
mtext(eq2,side=3,adj=0,cex=0.7)
mtext(bquote(r^2 == .(r2.2)),adj=1,cex=0.7)

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM