Created
January 12, 2022 06:13
-
-
Save RamiKrispin/6012277c727c6e5dc39b52583ce97e3f to your computer and use it in GitHub Desktop.
Regression plot with R-sqr value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Adding regression line to a plot | |
set.seed(1234) | |
# Creating a random dataset | |
x <- rnorm(n = 1000, mean = 10, sd = 3) | |
y <- 2 * x + 10 + rnorm(n = 1000, mean = 0, sd = 4) | |
d <- data.frame(y = y, | |
x = x) | |
head(d) | |
# fitting regression model | |
fit <- lm(y ~ x, data = d) | |
summary(fit) | |
# The R-sqr valu | |
summary(fit)$adj.r.squared | |
library(plotly) | |
# Plotting the data | |
plot_ly(data = d, | |
x = ~ x, | |
y = ~ y, | |
type = "scatter", | |
mode = "markers", | |
name = "Data") %>% | |
add_lines(x = ~ x, | |
y = fitted(fit), | |
name = "Regression Line", | |
line = list(color = "red", width = 3, dash = "dash")) %>% | |
# Add the R^2 as text annotation | |
add_annotations(text = paste("R^2 = ", round(summary(fit)$adj.r.squared, 2), sep = ""), | |
xref = "paper", | |
yref = "paper", | |
x = 0.1, | |
y = 0.9, | |
showarrow = FALSE) %>% | |
layout(title = "My Title...", | |
yaxis = list(title = "Y axis"), | |
xaxis = list(title = "X axis"), | |
margin = list(t = 60, b = 60)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment