R : Add Linear Regression Equation and RSquare to Graph

Live Online Training : Predictive Modeling using SAS

- Explain Advanced Algorithms in Simple English
- Live Projects & Case Studies
- Domain Knowledge
- Job Placement Assistance

In this article, we would see how to add linear regression equation and r-squared to a graph in R. It is very useful when we need to document or present our statistical results. Many people are familiar with R-square as a performance metrics for linear regression. If you are novice in linear regression technique, you can read this article - Linear Regression with R

Create Sample Data

The following program prepares data that is used to demonstrate the method of adding regression equation and rsquare to graph.
x = c(1:250)
mydata= data.frame(x, y= 30 + 2.5 * x + rnorm(250,sd = 25))
Load Required Library
R Function
linear = function(k) {
  z <- list(xx = format(coef(k)[1], digits = 2),
            yy = format(abs(coef(k)[2]), digits = 2),
            r2 = format(summary(k)$r.squared, digits = 3));
  if (coef(k)[2] >= 0)  {
    eq <- substitute(italic(hat(y)) == xx + yy %.% italic(x)*","~~italic(r)^2~"="~r2,z)
  } else {
    eq <- substitute(italic(hat(y)) == xx - yy %.% italic(x)*","~~italic(r)^2~"="~r2,z)  
fo = y ~ x
linplot <- ggplot(data = mydata, aes(x = x, y = y)) + geom_smooth(method = "lm", se=FALSE, color="black", formula = fo) +  geom_point()
linplot1 = linplot + annotate("text", x = 100, y = 500, label = linear(lm(fo, mydata)), colour="black", size = 5, parse=TRUE)
Regression Line

R Tutorials : 75 Free R Tutorials

Statistics Tutorials : 50 Statistics Tutorials

About Author:

Deepanshu founded ListenData with a simple objective - Make analytics easy to understand and follow. He has close to 7 years of experience in data science and predictive modeling. During his tenure, he has worked with global clients in various domains like retail and commercial banking, Telecom, HR and Automotive.

While I love having friends who agree, I only learn from those who don't.

Let's Get Connected: Email | LinkedIn

Get Free Email Updates :
*Please confirm your email address by clicking on the link sent to your Email*

Related Posts:

0 Response to "R : Add Linear Regression Equation and RSquare to Graph"

Post a Comment

Next → ← Prev