I want to add R2 values to a graph I generated using ggplot2. Below is my code:
ggplot(mad[["Timeline"]], aes(x=Year, y=gen)) + geom_point(color="purple") + geom_smooth(aes(x=Year,y=gen),color="purple",method="glm", formula = y~x, method.args=list(family=gaussian(link="log"))) +
geom_point(data=mad[["Timeline"]], mapping = aes(x=Year, y=pro), color="orange") + geom_smooth(aes(x=Year,y=pro),color="orange",method="glm",formula = y~x, method.args=list(family=gaussian(link="log"))) +
geom_point(data=mad[["Timeline"]], mapping = aes(x=Year, y=met), color="blue") + geom_smooth(aes(x=Year,y=met),color="blue",method="glm", formula = y~x, method.args=list(family=gaussian(link="log")))
Just to try on one curve, I used
lm_eqn <- function(df){
m <- lm(y ~ x), df);
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.expression(eq));
}
with
ggplot(mad[["Timeline"]], aes(x=Year, y=gen)) + geom_point(color="purple") + geom_smooth(aes(x=Year,y=gen),color="purple",method="glm", formula = y~x, method.args=list(family=gaussian(link="log"))) + geom_text(label = lm_eq(mad[["Timeline"]]), parse = TRUE) +
geom_point(data=mad[["Timeline"]], mapping = aes(x=Year, y=pro), color="orange") + geom_smooth(aes(x=Year,y=pro),color="orange",method="glm",formula = y~x, method.args=list(family=gaussian(link="log"))) +
geom_point(data=mad[["Timeline"]], mapping = aes(x=Year, y=met), color="blue") + geom_smooth(aes(x=Year,y=met),color="blue",method="glm", formula = y~x, method.args=list(family=gaussian(link="log")))
but I got this error: Error in eval(predvars, data, env) : object 'y' not found.
I want to add the R2 values for the gen, pro, and met curves, but I am not sure how to proceed.