I want to compare two linear regression plots and print their respective eqns on the plot or slightly above. I don't know how to make the equation appear with the r2 value and placed on their respective plot (ideally on one line). The text file is simply as follows:
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
Thanks for the help.
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)
The text for the first plot should be placed before adding the second plot. The following code was used to generate the sample figure based on your data. I added cex=0.7
to the arguments for mtext()
to reduce the size of the text and avoid the equation interfering with the r-squared value.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.