Add regression line equation and R^2 on graph


š Title: How to Add Regression Line Equation and R^2 on a ggplot
Graph
š Hey there! Are you struggling with adding a regression line equation and R^2 on a ggplot
graph? Don't worry, I've got you covered! In this blog post, I'll walk you through a step-by-step guide to achieving this. š
ā
Problem: You want to visualize a regression line equation and R^2 on your ggplot
graph but not sure how to do it.
āļø Solution: Follow these simple steps to add the regression line equation and R^2 on your graph:
First, make sure you have the
ggplot2
library installed. If not, install it using the following code:
install.packages("ggplot2")
library(ggplot2)
Now, let's create some dummy data for our example. Run the following code to generate a dataset:
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
We'll use the
geom_smooth()
function with the "lm" method to add a regression line to our plot. Additionally, we need to setse = FALSE
to remove the confidence interval. Include theformula = y ~ x
argument to specify the regression equation. We'll also addcolor = "black"
to set the line color. Finally, don't forget to includegeom_point()
to add the data points. Run the following code:
p <- ggplot(data = df, aes(x = x, y = y)) +
geom_smooth(method = "lm", se = FALSE, color = "black", formula = y ~ x) +
geom_point()
At this point, we have our basic graph. To add the regression line equation and R^2, we'll need to use the
annotate()
function. Add the following lines of code:
model <- lm(y ~ x, data = df)
eqn <- substitute(paste("Equation: ", y == a + b %.% x, ", R^2 = ", r2),
list(a = format(coef(model)[1], digits = 2),
b = format(coef(model)[2], digits = 2),
r2 = format(summary(model)$r.squared, digits = 2)))
p +
annotate("text", x = max(df$x), y = max(df$y), label = as.character(as.expression(eqn)),
parse = TRUE, hjust = 1, vjust = 1, color = "red", fontface = "bold")
Finally, run the code, and you'll have your
ggplot
graph with the regression line equation and R^2 displayed on it. š
š£ So there you have it! You can now easily add a regression line equation and R^2 on your ggplot
graphs using these simple steps. Hope this guide was helpful in solving your problem! If you have any further questions or ideas, feel free to share them in the comments below. Happy coding! šš»
Take Your Tech Career to the Next Level
Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.
