I found a function that adds a regression line equation on graph. Adding Regression Line Equation and R2 on graph If I copy the function and data sample, everything works fine. But when I try to adapt the code, I get the message, that Y can't be found.
The Function:
lm_eqn <- function(df){
m <- lm(y ~ x, df);
eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
list(a = format(coef(m)[1], digits = 2),
b = format(coef(m)[2], digits = 2),
r2 = format(summary(m)$r.squared, digits = 3)))
as.character(as.expression(eq));
}
My data sample and adapted code:
library(tidyverse)
set.seed(1)
id <- 1:5000
zip <- sample(100:200, 5000, replace = TRUE)
outcome <- rbinom(5000, 1, 0.23)
df <- data.frame(id, outcome, zip) %>% as_tibble()
new_df <- df %>% group_by(zip) %>% summarise(ratio = mean(outcome))
library(ggplot2)
t <- ggplot(data = new_df, aes(x = zip, y = ratio)) +
geom_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x) +
geom_point()
t1 <- t + geom_text(x = 25, y = 300, label = lm_eqn(df), parse = TRUE)
Error in eval(predvars, data, env) : object 'y' not found
Where did I make the mistake? Thanks in advance!