Is there any method of visualizing R-squared and regression line equation in R.If yes, explain with an example

504    Asked by Dannasahi in Data Science , Asked on Nov 15, 2019
Answered by Danna sahi

Yes it is possible to graph regression line using ggplot

Let us build a simple linear regression taking assumed values of X and Y.

library(ggplot2)

Let us create a dataframe of following data

data <- data.frame(x = c(1:100))

data$y <- 3 + 4* data$x + rnorm(100, sd = 40)

Now let us plot with the following data

p <- ggplot(data = df, aes(x = x, y = y)) + geom_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x) +geom_point()

Now let us create an equation to visualize regression line

equation <- function(data){

  m <- lm(y ~ x, data);

 eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,

list(a = format(unname(coef(m)[1]), digits = 2),

   b = format(unname(coef(m)[2]), digits = 2),

   r2 = format(summary(m)$r.squared, digits = 3)))

  as.character(as.[removed]eq));

}

p1 <- p + geom_text(x = 25, y = 300, label = equation(data), parse = TRUE)



Your Answer

Interviews

Parent Categories