I'm trying to plot a regression line with some data in x and y. I create a function which calculates the coefficients of the line, then I call it in "p" to show the equation in the title.
library(ggplot2)
x <- c(1,2,2,2,3,3,4,5,5,6,6,6,6,7,8,9,9,11,11,11,15,15,16,16,16,16,17,18,18,18)
y <- c(1,2,4,3,3,2,5,4,6,3,7,7,6,7,8,4,5,4,9,9,13,14,15,15,15,16,17,19,19,20)
eq = function(x) {
lm_coef <-list( a = round(coef(x)[2], digits = 2), b = round(coef(x)[1], digits = 2), r2 = round(summary(x)$r.squared, digits = 2));
lm_eq <- substitute(y = a * x + b )
as.character(as.ep(lm_eq));
}
p <- ggplot(data=NULL, aes(x=x, y=y)) +
geom_point() +
geom_smooth(method=lm, se=FALSE, color="black") +
scale_y_log10() +
ggtitle(eq(x))+
theme(plot.title= element_text(hjust=0.5, size=20))
p
The problem is that I get this error message :
"$ operator is invalid for atomic vectors".
I know that the problem comes from my call in ggtitle(equation(x))
but I don't know how to solve it.
If you have an idea, thanks