Alvin
Alvin

Reputation: 57

Linear equation on plot

I wonder how to add linear equation on plot same as R-squared in the bottom right part. I will be grateful for the help.

plot(dat$rain_5, dat$r5,
     main="Rollesbroich-5",
     ylab="Lysimeter (mm/hour)",
     xlab="Rain gauge (mm/hour)",
     xlim=c(0,25), ylim=c(0,25),
     type="p",
     col="red",
     cex.lab=1.3,
     cex.main=1.5, mgp=c(2,0.5,0),
     pch=16)
linear.model<-lm(dat$r5 ~ dat$rain_5, data = dat)
summary(linear.model)
modsum = summary(linear.model)
r2 = modsum$r.squared
rp[1] = substitute(expression(italic(R)^2 == MYVALUE), 
                   list(MYVALUE = format(r2,dig=4)))[2]
legend('bottomright', legend = rp, bty = 'n', cex=1.2)
abline(linear.model, lwd=2)

Upvotes: 1

Views: 74

Answers (1)

Darren Tsai
Darren Tsai

Reputation: 35554

Take the built-in dataset iris for example:

model <- lm(Sepal.Length ~ Petal.Length, data = iris)
modsum <- summary(model)
r2 <- modsum$r.squared
b <- round(coef(model), 3)
rp <- substitute(atop(italic(R)^2 == MYVALUE, y == b1~x + b0),
                 list(MYVALUE = round(r2, 4), b0 = b[1], b1 = b[2]))
plot(Sepal.Length ~ Petal.Length, iris)
abline(model, col = 2)
legend("bottomright", legend = rp, bty = 'n', cex = 1.5)

Upvotes: 2

Related Questions